jQuery:等到多个GET请求被成功处理
我需要发出多个$ .get请求,处理它们的响应,并在同一个数组中记录处理结果。 代码如下所示:
$.get("http://mysite1", function(response){ results[x1] = y1; } $.get("http://mysite2", function(response){ results[x2] = y2; } // rest of the code, eg, print results
在继续我的其余代码之前,是否确保所有成功函数都已完成?
有一个非常优雅的解决方案: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/
$.when
允许你组合多个Deferred
s(这是$.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. });