jQuery:等到多个GET请求被成功处理

ami*_*mir 21 jquery wait get-request

我需要发出多个$ .get请求,处理它们的响应,并在同一个数组中记录处理结果.代码如下所示:

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

// rest of the code, e.g., print results
Run Code Online (Sandbox Code Playgroud)

在继续我的其余代码之前,有没有确保所有成功函数都已完成?

Nik*_*iko 38

有一个非常优雅的解决方案:jQuery Deferred对象.$ .get返回一个实现Deferred接口的jqXHR对象 - 这些对象可以像这样组合:

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

$.when(d1, d2).done(function() {
    // ...do stuff...
});
Run Code Online (Sandbox Code Playgroud)

更多信息,请访问http://api.jquery.com/category/deferred-object/http://api.jquery.com/jQuery.when/


jos*_*736 10

$.when让你组合多个Deferreds($.ajax返回的是什么).

$.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.
});
Run Code Online (Sandbox Code Playgroud)