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複数の を組み合わせることができますDeferred(これが$.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 に答える