我进行了 ajax 调用,并且调用了一个工作正常的 setInterval 函数。不幸的是,当我试图阻止它时,它不起作用。
function test(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (str=="?stage=3"){
test('?stage=4');
}
if (str=="?stage=4"){
document.getElementById("main").innerHTML+=xmlhttp.responseText;
prog=window.clearInterval(prog);
}else{
document.getElementById("main").innerHTML+=xmlhttp.responseText;
}
}
else
{
if (str=="?stage=3"){
var prog = self.setInterval( "ajaxrequest('progress_track.php', 'main')", 1000 );
}
}
}
xmlhttp.open("GET","test.php"+str,true);
xmlhttp.send();
}
非常感谢任何帮助。
编辑:
我重新编写了代码,因为我发现它以某种方式调用了 setinveral 函数的 3 倍。这段代码只调用了 2 次。我只是不明白为什么。
var prog = 0;
function test(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200 && str=="?stage=3")
{
test('?stage=4');
}else{
if( str=="?stage=3"){
prog = self.setInterval( "ajaxrequest('progress_track.php', 'main')", 1000 );
}
}
if (xmlhttp.readyState==4 && xmlhttp.status==200 && str=="?stage=4")
{
prog=window.clearInterval(prog);
}
if (xmlhttp.readyState==4 && xmlhttp.status==200 && str!="?stage=4" && str!="?stage=3")
{
document.getElementById("main").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php"+str,true);
xmlhttp.send();
}
但是cleariterval仍然不起作用。
编辑:
我发现了问题。这段代码永远不会达到这种状态:
if (xmlhttp.readyState==4 && xmlhttp.status==200 && str=="?stage=4")
{
prog=window.clearInterval(prog);
}
现在唯一的问题是为什么不呢?
最佳答案
您需要在更高的范围内声明“prog”。您可以将其移到函数声明之外:
var prog;
function test(str) {
...
if (str=="?stage=3"){
prog = self.setInterval(
"ajaxrequest('progress_track.php', 'main')", 1000
);
}
...
}
按照您现在的方式,当您调用 clearInterval()
时,prog
是未定义的
关于php - Clearinterval 在 ajax 请求中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227534/