jquery ajax async stopped

jquery ajax async stopped

本文关键字:stopped async ajax jquery      更新时间:2023-09-26

我在循环中运行ajax请求,将async设置为false,并且在计数器为2时停止。下面是脚本

var x = 0;
for(i=0; i<10; i++){
    $.ajax({
          async: false,
          global: isGlobal,
          type: 'POST',
          url: url,
          dataType: 'json',
          data: JSON.stringify(body),
          headers: {'Content-type':'application/json', 'Accept':'application/json'},
          success: function(result){
            x = result.something.value;
          },
          error: function(){
              callback(false);
          }
    });
    console.log(x); // debug x value
}

知道为什么这不能正常工作吗?PS: url是跨域

我自己解决这个问题。这里是工作脚本,以防你,访问者,有和我一样的问题。

var theList = [/*LIST GOES HERE*/];
var yourGlobalVar = '';
i = 0;
(function gcr(){
  var body = {
    ID: theList[i].ID
  };
  $.ajax({
          async: false,
          global: isGlobal,
          type: 'POST',
          url: url,
          dataType: 'json',
          data: JSON.stringify(body),
          headers: {'Content-type':'application/json', 'Accept':'application/json'},
          success: function(result){
            yourGlobalVar += result.anything.value;
            if(i < theList.length - 1){
              // wait for the response then call itself
              i++;
              gcr();
            }
          }
    });
})();