2014-06-09 71 views
0

我运行async集Ajax请求false内环路,并在停止时在这里2.柜台是脚本jQuery的AJAX异步停止

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是跨域

+0

你不是真的在做阿贾克斯吗?那什么意识?请代码不只是说话,我迷路了! –

+0

我需要做的是为每个请求改变'x'变量,就是这样,如果我的代码错了,请指向正确的方向。谢谢 –

+0

Ajax代表* Asynchronous Javascript And Xml *,你刚刚通过将async设置为false来删除* Asynchronous *部分,所以它不是真正的ajax,它是sjax,*同步的Javascript和Xml *,这有什么好处? – adeneo

回答

0

我解决了这个问题我的自我。这里是工作脚本,以防你和访问者遇到同样的问题。

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(); 
      } 
      } 
    }); 
})();