2012-12-27 108 views
3

假設我有一個循環,我在其中調用WinJS.xhr()多個地址。在響應處理程序中,有沒有一種方法可以確定響應正在處理的地址?要麼通過從傳遞給處理程序或通過手動傳遞其他東西的XmlHttpRequest對象辨別它?從WinJS.xhr獲取URL響應

我一直在尋找the documentation以及檢查調試器中的響應,但一直未能找到任何東西。

回答

4

我不認爲這些信息是在響應中,但它不需要。每個xhr呼叫都有自己的Promise,該呼叫是針對該特定呼叫返回的。我喜歡做這種方式...

//start with an array of some kind 
var urls = [ 
    "http://something.com/1", 
    "http://something.com/2", 
    "http://something.com/3", 
]; 

//map the array to a list of calls adding your url in so you have it 
var results = urls.map(function(u) { 
    return {url:u, response:WinJS.xhr({url:u})}; 
} 

然後你就可以循環的結果陣列,並且具有URL。你可能想把它包裝在另一個承諾中,這樣整個事情就是異步的。

function xhrCallsAsync() { 

    //start with an array of some kind 
    var urls = [ 
     "http://something.com/1", 
     "http://something.com/2", 
     "http://something.com/3", 
    ]; 

    //map the array to a list of calls adding your url in so you have it 
    var results = urls.map(function(u) { 
     return {url:u, response:WinJS.xhr({url:u})}; 
    } 

    //return a Promise that completes when all of the Promises are complete 
    return WinJS.Promise.join(results); 
} 

希望幫助!

+0

我在這裏使用的其他調整是讓鏈中的第一個承諾是一個包裝,並將結果作爲通過.join彙集的豐富對象返回。例如(愚蠢的格式,對不起):WinJS.Promise.join({url:yourSourceUrl,xhr:WinJS.xhr({url:yourSourceUrl}),})。then(function(result){// get result.url result.xhr作爲完成的結果}); –

+0

真棒建議。我最終做的是在'map()'調用中直接在'.done()'的'.done()'中使用'u'。 (所以沒有額外的循環。)就像一個魅力! – David

+0

@Jeremy Foster這不適合我。當我調用'xhrCallsAsync()。done(function(results){});'結果對象具有包含url和xhr的數組。所以它沒有任何Ajax電話呢?我是否需要遍歷結果,然後爲每個結果調用result.xhr.done()以獲得實際響應? – sanjeev