无法从包含 clearInterval/setInterval 的 ajax/jquery/JavaScript 更新

Unable to update the visibility of an html <div> block from ajax/jquery/JavaScript containing clearInterval/setInterval

本文关键字:ajax jquery JavaScript 更新 setInterval 包含 clearInterval      更新时间:2023-09-26
块的可见性。

我是ajax/JS/jQuery的初学者。我有一个 ajax 调用来检查服务器上是否有可用的文件。为了实现这一点,我使用 setInterval() 和 clearInterval()。在成功调用 ajax 时,我在将显示属性设置为 html 元素时遇到问题。任何指导都非常感谢。

<html>
<head>
</head>
<body >
<div id="export-div" hidden>
Click Me
</div>
<script type="text/javascript">
    function foo_func() {
            $('#export-div').show(); //*****tried, but does not work*******
            var foo = document.getElementById("export-div");
            foo.style.display = "block"; // **********Does not work***************
            alert(foo.innerHTML); //Alert box correctly pops up with text 'Click Me'
            clearInterval(timerForLoadingResult); //I initially had this inside the ajax success/done function
            }
</script>
<script type="text/javascript">
    var timerForLoadingResult = setInterval(checkServerForFile,5000); //call the function in every 5 seconds and write ajax in that function.
    function checkServerForFile() {
                    var chck = $.ajax("<?php echo "/Results/".$filename; ?>") //searches for a file on server
                    chck.success(function(){
                    alert( "Ajax call successful" ); //This alert box also pops up
                    foo_func();
                    });
            };
</script>
</body>
</html>

我添加了修复程序 http://jsfiddle.net/20dw5ex8/6

使用 jquery show() 和 hide() 函数。喜欢

$('#export-div').show(); or $('#export-div').hide();

您可以在开头设置隐藏您的div

<div id="export-div" hidden> Click Me</div>

并在返回 ajax 调用时显示它。

不确定当您

请求"<?php echo "/Results/".$filename; ?>"时,您期望什么,但似乎 if 总是失败,并且您的done方法总是被触发。

以下是您的$.ajax()请求的方法:

  • .success():仅在收到状态为 200 时触发
  • .error():收到状态不是 200 时触发(错误)
  • .done() : 始终发射

内容将不会显示,因为您有一个 css 绝对位置,并且您将元素从窗口发送出去。