如何在 PHP 脚本通过 ajax 完成执行后停止 setInterval


how to stop setInterval after php script is done executing through ajax

我已经搜索了这个问题的答案,我没有找到它的原因可能只是我从一开始就完全搞砸了我的脚本,所以请任何可以帮助我的人非常感谢它。

我有一个javascript函数,它在单击表单提交时触发并运行对script1.php的ajax调用,然后使用setInterval启动计时器。 setInterval正在调用另一个javascript函数来轮询script1的输出文件.php因此我们可以将新数据添加到屏幕上。这部分工作正常。

但是,我想在 script1.php 完成处理时停止计时器。我该怎么做?我尝试在script1中放入clearInterval(myTimer).php作为它运行的最后一个语句,它似乎显示在浏览器中,但它并没有停止计时器。

<script type="text/javascript">
var myTimer;
var file1 = "script1.php";
var file2 = "script2.php";

function startTimer(myTimer) {
  myTimer = window.setInterval(loadData, 2000);
}
function stopTimer() {
  clearInterval(myTimer);
}
function startData()
{
ajaxRequest(file1,data);
startTimer(myTimer);
}

function loadData()
{
ajaxRequest(file2)
}

</script>

<form action="index.php" method="post">
<div style="text-align:left;width:300px;">
<textarea style="width:300px;height:200px;"> </textarea><BR>
<button type="button" onclick="startData()">get data</button>
</div>
</form>
<div id="myDiv" style="text-align:left;width:500px;border:solid 1px #ccc;padding:50px;">
please enter data above
</div>

是的,你搞砸了。你应该让 PHP 将数据直接返回到执行 AJAX 调用的脚本。

在 AJAX 成功时,PHP 脚本输出的任何文本都可用于成功回调。

如果您使用的是 JQuery,它将像以下一样简单:

$.ajax({
   url: 'someurl',
   success: function(response) {
      // do whatever with response
   }
});

您将myTimer作为参数传递给startTimer 。 这使得myTimer成为要startTimer的局部变量。 因此,它不会更新全局myTimer

它应该是:

function startTimer() {
  myTimer = setInterval(loadData, 2000);
}
function stopTimer() {
  clearInterval(myTimer);
}

然后你只需要打电话给startTimer()stopTimer().

当你开始你的间隔时,把它分配给任何PUblally可访问的变量,说"INTERVAL_ITEM"

以及当您的回复达到明确间隔(INTERVAL_ITEM);