javascript - Ajax 只运行一次

标签 javascript php jquery ajax

我有一个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 会出错,并在一次迭代后默默地死亡。

删除该行可以使代码正常运行,您只需将数据存储在另一个变量中即可正常工作。

Here's a fiddle with the functional code with just that line commented out.

关于javascript - Ajax 只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358619/

相关文章:

php - 调用未定义的方法 Illuminate\Auth\GenericUser::fill()::when update

javascript - jQuery QuickFit 调整不适合 div 的文本大小

JavaScript:不会停止执行以下行的回调

javascript - 创建可扩展的多层系统图

php - 将 php 数组映射到嵌套的 json

php - 如何使用 JAXL 库发送/接收聊天消息(XMPP 技术、PHP、Openfire 服务器)

jquery - 在第一句中添加一个元素

jquery - ColorBox - 将 ALT 文本添加到图库图像?

javascript - Protractor 测试: options to force refresh when URL hash changes

javascript - 将 jQuery 添加到 wordpress 页面以显示时间/日期选择器