为AJAX做循环吗?

时间:2015-12-04 21:10:21

标签: javascript jquery ajax loops asynchronous

我试图循环ajax请求10次。我注意到一些奇怪的错误,例如int为10,10次。我搜索过并发现它与AJAX异步相关。我希望有一些等待,直到ajax请求完成然后继续。

提前致谢。

FragmentTransaction

3 个答案:

答案 0 :(得分:2)

If your success handler is referring to int, then yes, by the time it runs int will always be 0, since that's long after the loop has completed.

If you really want the calls to run in succession, with a different value each time, move the call to a function, and call it as needed from the ajax success handler:

function myAjax(int) {
  if (int >= 10)
    return;

  $.ajax({   //...
     success:function(response){ 
       int++;
       // whatever we need to do with int and the response

       myAjax(int);
     }
  });
}

myAjax(0);

答案 1 :(得分:1)

您可以将参数async: false设置为ajax对象。

$.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        async: false,
        error: function(){
            return true;
        },
        success: function(msg){
        }
    });

答案 2 :(得分:0)

我相信这是您正在寻找的代码:

for (var int = 0; int < 10; int++) {
    (function (int) {
        $.ajax({
            url : 'process.php',
            success : function() {
                alert("TEST");
            }
        });
    })(int);
}

以下是一些链接,其中包含有关其工作原理的更多信息: jQuery AJAX calls in for loop [duplicate] JavaScript closure inside loops – simple practical example