jQuery: Wait till multiple GET requests are successully processed

泪湿孤枕 提交于 2019-11-27 02:40:27

问题


I need to issue multiple $.get requests, process their responses, and record the results of the processing in the same array. The code looks like this:

$.get("http://mysite1", function(response){
  results[x1] = y1;
}
$.get("http://mysite2", function(response){
  results[x2] = y2;
}

// rest of the code, e.g., print results

Is there anyway to ensure that all the success functions have completed, before I proceed to the rest of my code?


回答1:


There is a very elegant solution: the jQuery Deferred object. $.get returns a jqXHR object that implements the Deferred interface - those objects can be combined like this:

var d1 = $.get(...);
var d2 = $.get(...);

$.when(d1, d2).done(function() {
    // ...do stuff...
});

Read more at http://api.jquery.com/category/deferred-object/ and http://api.jquery.com/jQuery.when/




回答2:


$.when lets you combine multiple Deferreds (which is what $.ajax returns).

$.when( $.get(1), $.get(2) ).done(function(results1, results2) {
    // results1 and results2 will be an array of arguments that would have been
    // passed to the normal $.get callback
}).fail(function() {
    // will be called if one (or both) requests fail.  If a request does fail,
    // the `done` callback will *not* be called even if one request succeeds.
});


来源:https://stackoverflow.com/questions/9898813/jquery-wait-till-multiple-get-requests-are-successully-processed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!