繁体   English   中英

Ajax 只运行一次

[英]Ajax running only once

我有一个 ajax 函数,我希望它运行 1912 次,但由于某种原因它只运行一次。 我正在使用 startAt 和 stopAt 来确定它何时应该停止运行,但由于某种原因它不起作用。 我究竟做错了什么?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript"> 
function callAjax(gotoUrl, link, startAt, stopAt, output) {

  $.ajax({
    type: "POST",
    url: gotoUrl,
    data: { link : link },
    error: function(xhr,status,error){
      alert("error");
    },
    success:function(data) {
      document.getElementById(output).innerHTML += startAt;
    },
    complete:function(data) {
      startAt++;
      var link = data; 
      if (startAt < stopAt) {
        setTimeout(function(){ 
            callAjax(gotoUrl, link, startAt, stopAt, output) 
        }, 100);
      }
    }
  });

} //end of function callAjax()  
</script>

<body onload = 'callAjax("test1.php", "link", 1, 1912, "output")'>
<div id = "output"></div>

结果:

1

预期结果:

1912

问题出在这一行:

var link = data; 

您正在将link的值重新分配为返回的数据。

然后您立即在超时内调用它:

callAjax(gotoUrl, link, startAt, stopAt, output)

但是link不再是一个链接,它是一个对象,因此 jquery 出错,并在一次迭代后无声地死亡。

删除该行使代码功能正常,您只需要将数据存储在另一个变量中,它就会起作用。

这是功能代码的小提琴,仅注释掉了该行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM