0

私は複数の延期されたAjax呼び出しを処理しており、それらのデータへのアクセス方法について動的になりたいと思っています。いくつかのパラメーターを.thenコールバックにハードコーディングしてそれぞれを個別に使用するのではなく、argumentsオブジェクトをループしてデータにアクセスしたいと思います。これは正常に機能しますが、jsonからどのデータがどのAjax呼び出しからのものであるかを判別できない場合を除きます。これは、promiseオブジェクトから(何らかの方法で)URLを決定するか、Ajax呼び出しが実行された順序を把握し、データが同じ順序であると想定することで解決できます。

これまでの私のコードは次のとおりです(私がやろうとしていることを説明するためにモックアップされています):

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)
})

ありがとう!サラ

4

2 に答える 2

0

やってみよう

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) 
});
于 2012-01-12T15:28:21.480 に答える
0

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呼び出しの成功ハンドラーにあります。上記の例。

于 2012-07-18T15:23:53.640 に答える