同步ajax调用问题

时间:2014-02-09 12:06:28

标签: jquery ajax

我有这样的事情:

for(var i=0;i<deserializedData.forms.length;i++){
        $.ajax({
            type: "POST",
            url: "../getFormMetaData/",
            cache:false,
            data: {'a':'a'},
            success: getFormMetaDataCallback,
            error: displayAjaxError
        });
    }

当电流结束时,我可以以某种方式进行ajax调用吗?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

var ajax_index = 0; // which request we are currently processing
var arr = [ all, ajax, requests ]; // array of data for each request

// Execute a request
function doRequest( index ){
  $.ajax({
    type: "POST",
    data: arr[ index ]
    ...
    success: function(){
      // Once the request has responded, increase the index counter
      // and execute the next request
      ajax_index++;
      if ( ajax_index > arr.length ){
        // Continue executing requests if there are still remaining
        doRequest( ajax_index );
      }
    }
  });
}
doRequest( ajax_index );

通过使用函数包装AJAX请求,您可以每次使用不同的索引多次调用此函数,以便按顺序执行所有请求。

答案 1 :(得分:1)

使用jQuery when函数等待你的承诺。

http://api.jquery.com/jQuery.when/

可在此处找到更详细的答案:Wait until all jQuery Ajax requests are done?

要在循环中使用它,必须在数组中通过jQuery.ajax保存延迟对象返回,并将该数组传递给jQuery.when函数。

var deferredResults = [];
deserializedData.forms.forEach(function () {
    var deferredResult = $.ajax({
        ... // use no success or error callbacks here
    });
});
jQuery.when(deferredResults).done(function() {
    // if you don't know how many calls you made, use the function arguments.
    // this line turns the arguments objects into an array you can use safely.
    var results = Array.prototype.slice.apply(arguments)

});