我已经搜索了这个问题的答案,而我没有找到它的原因可能只是因为我从一开始就完全搞砸了我的脚本,所以请任何可以帮助我的人,我非常感激。
我有一个 javascript 函数,它触发表单提交的 onClick 并运行对 script1.php 的 ajax 调用,然后使用 setInterval 启动计时器。 setInterval 正在调用另一个 javascript 函数来轮询 script1.php 的输出文件,以便我们可以获得添加到屏幕的新数据。这部分工作正常。
但是,我想在 script1.php 处理完成后停止计时器。我该怎么做呢?我尝试在 script1.php 中放入一个clearInterval(myTimer) 作为它运行的最后一个语句,它似乎显示在浏览器中,但它并没有停止计时器。
<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
}
});
关于php - php脚本通过ajax执行完成后如何停止setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402665/