0

我正在处理多个延迟的 Ajax 调用,我希望动态了解我如何访问他们的数据。我不想将多个参数硬编码到 .then 回调中并单独使用每个参数,而是希望循环访问参数对象以访问数据。这工作正常,除了我无法从 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 回答