2012-01-12 44 views
0

我正在處理多個延期Ajax調用,我想動態地瞭解我如何訪問他們的數據。而不是將幾個參數硬編碼到.then回調函數中並單獨使用每個參數,我想循環訪問參數對象以訪問數據。這工作正常,除非我無法從json確定哪些數據來自哪個Ajax調用。我可以通過確定承諾對象的URL(以某種方式)或者確定Ajax調用執行的順序和假定數據的順序相同來解決此問題。來自多個延遲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) 
}) 

謝謝! 薩拉

+0

我不確定'apply'是如何工作的,但是你不能在你的'promises'數組中添加每個調用的URL嗎?你可能會把你的promises數組轉換成一個對象數組''promises = [{url:「example.php」,fn:$ .get(「example.php」,{},function(){})},.. 。]' – 2012-01-12 15:29:53

+0

我可以做到這一點,但它會讓jquery承諾進入when.apply調用變得複雜。如果你只是做一個直接的Ajax調用,這個承諾是免費返回的。 – saranicole 2012-01-12 15:44:32

回答

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

}); 

正如你提到的接收對象的 「那麼」 是所有deferreds成功處理程序。因此,將這些信息配對的唯一真正方法是在Ajax調用的成功處理程序中。上面的例子。

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) 
}); 
+0

試過了,我得到了一個類型錯誤,承諾對象沒有方法成功。感謝您的深思熟慮的迴應! – saranicole 2012-01-12 15:42:43

+0

@saranicole - 我嘗試了不同的扭曲。我假設你想在你的jsonarray中返回的數據,並且它應該由url鍵入?如果我錯了,請糾正我。 – Skyrim 2012-01-12 15:48:49

+0

@saranicole你使用的是什麼版本的jquery?在最新版本中,'.success()'已被替換爲'.done()',因此請嘗試使用它。 – 2012-01-12 15:51:12