将来自多个延迟Ajax调用的数据与其调用者配对

时间:2012-01-12 15:07:34

标签: jquery ajax deferred

我正在处理多个延迟的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)
})

谢谢! 萨拉

2 个答案:

答案 0 :(得分: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) 
});

答案 1 :(得分: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调用的成功处理程序中。上面的例子。