繁体   English   中英

jQuery ajax异步停止

[英]jquery ajax async stopped

我在循环内运行async并将async设置为false的ajax请求,并在计数器为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();
            }
          }
    });
})();

暂无
暂无

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

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