複数の延期されたAJAXコールからのペアリングデータは発信者と

StackOverflow https://stackoverflow.com/questions/8837260

  •  27-10-2019
  •  | 
  •  

質問

私は複数の延期されたAJAXコールを使用していますが、データにどのようにアクセスするかについてダイナミックになりたいと思います。 .then callbackにいくつかのパラメーターをハードコードし、それぞれを個別に使用するのではなく、引数オブジェクトをループしてデータにアクセスしたいと思います。これは正常に機能しますが、JSONからどのデータがどのデータが呼び出されるかを判断できません。 PromiseオブジェクトからURLを決定するか、Ajaxが実行する順序を実行し、データが同じ順序であると仮定することで、これを解決できます。

これまでのところ私のコードです(私がやろうとしていることを説明するためにock笑されました):

promises = [ 
    $.get("example.php", {}, function(){}),
    $.get("list.php", {}, function(){}),
    $.get("test.php", {}, function(){}),

]

$.when.apply(null, promises).then( function() {
     jsonarray = []
     $.each(arguments, function(index, value){
         // this is what I would like to work but doesn't
         // promises[index].success.url is how I imagine accessing 
         //"list.php" or "test.php"
         if (jsonarray[promises[index].success.url] == null){
              jsonarray[promises[index].success.url] = []
         }
         jsonarray[promises[index].success.url] = value
         doSomethingWith(jsonarray)
     })

それぞれの引数とそれを生成したAjaxコールと一致させる別の方法はありますか?私がやりたくないのはこれです:

$.when.apply(null, promises).then( function(examplejson, listjson, testjson) {
         // this is lame
         exampledoSomethingWith(examplejson)
         listdoSomethingWith(listjson)
         testdoSomethingWith(testjson)
})

ありがとう!サラ

役に立ちましたか?

解決

http://jsfiddle.net/6ezsh/2/

$(function() {

    var objs = [{'one':1},{'two':2},{'three':3}];
    var urls = [];

    ajaxCall = function(i) {
        return $.ajax({
            url:'/echo/html/',
            method: 'POST',
            data: {id:i}
        }).done(function () {
            urls.push({obj:i,url:this.url});
        });   
    }

   $.when.apply($,
        objs.map(function(i) {
            return ajaxCall(i);
        })
    ).then(
        console.log(urls)
    );

});

前述のように、「Then」で受け取るオブジェクトは、すべての延期の成功ハンドラーです。したがって、この情報をペアにする唯一の本当の方法は、Ajaxコールの成功ハンドラーにあります。上記の例。

他のヒント

やってみよう

var urls = [
    "example.php",
    "list.php",
    "test.php"
];
var promises = [  
];

var jsonarray = {};
$.each(urls, function(index, value) {
    promises[index] = $.get(urls[index], {}, function(){});
    promises[index].success(function(data) {
        jsonarray[urls[index]] = data; //is this the value you want in the jsonarray??
    });
});

$.when.apply(null, promises).then( function() {
    doSomethingWith(jsonarray) 
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top