2012-03-27 7 views
17

複数の$ .getリクエストを発行し、レスポンスを処理し、処理の結果を同じ配列に記録する必要があります。コードは次のようになります。jQuery:複数の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 

私は自分のコードの残りの部分に進む前に、すべての成功の関数が完了していることを確認するために、とにかくありますか?

答えて

34

非常に洗練されたソリューション、jQuery Deferredオブジェクトがあります。

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/

+0

$ .get呼び出しの中で成功関数がある場合、その解決法はまだ機能しますか?私は前にそれを試していた、運がない! – amir

+0

はい、可能です。 – Niko

10

$.whenはあなたが何$.ajaxある(複数Deferredを組み合わせることができます。これらのオブジェクトは、次のように組み合わせることができます - $に.getは、繰延インタフェースを実装jqXHRオブジェクトを返します。戻る)。

$.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. 
}); 
関連する問題