22

我需要发出多个 $.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

在我继续执行其余代码之前,是否有确保所有成功功能都已完成?

4

2 回答 2

41

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

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

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

在http://api.jquery.com/category/deferred-object/http://api.jquery.com/jQuery.when/阅读更多内容

于 2012-03-27T22:50:14.913 回答
11

$.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.
});
于 2012-03-27T22:52:23.950 回答