2016-01-05 38 views
0

對不起,你們。我真的很討厭不得不問這個問題。我保證,我已經經歷了許多其他問題,因爲我的耐心允許,所以甚至看起來與切線相關。承諾解決後無法進入JSON響應

繼從下面的問題代碼:

我有以下幾點:

var XHR = []; 

//This parses some selections on a screen, which, in turn, informs the URL inside the loop. 
$("#list > input:checkbox:checked").each(function(){ 
    result = []; 
    var list = $(this).val(); 
    XHR.push($.ajax({ 
     type:'GET', 
     url:"https://a-place.com/subsite/webapp/_api/web/lists/getByTitle('"+list+"')/items?$select=" + select + "&$filter=" + filter + "&$expand=" + expand + "&$top=10000", 
     dataType: "json", 
     headers: {Accept:"application/json;odata=verbose"}, 
     complete:function(data){} 
    })); 
}); 

$.when(XHR).then(function(data){ 
    console.log(data); 
}); 

無論我做什麼,我都會得到那裏的承諾。我無法對它們做任何事情,試圖訪問所有實際對象所在的responseJSON屬性,什麼都不做。我已經嘗試在完整的回調函數中添加一個return語句,它看起來並沒有改變實際被推入XHR數組的內容。

理想情況下,應該從一個或多個匹配選定選項的SharePoint列表中返回一堆列表項,並將匹配項放入一個單獨的數組中,我可以使用這些數據。

編輯

嗯。好吧,根據建議,我已經試過:

success:function(data){} 

而且

success:function(data){return data.d.results;} 

並沒有什麼真正的控制檯改變,無論我是否使用$ .when.then或.done。

在此先感謝。

+0

想,也許你想'.done(...)'代替如果'。然後(...)' –

+0

我欣賞這個建議,但我已經試過了。相同的確切結果。 – ChrisPEditor

+0

而不是返回成功回調的結果,嘗試將其推入數組。 'result.push(data.d.results);'然後在「then」函數中,您將知道您已準備好所有結果,並且可以使用它。這裏不是奇特的解決方案,但應該工作。 –

回答

1

您可以嘗試收集你的成功回調所有結果,並在「然後」回調函數以後使用它:

var results = []; 
... 
success: function(data){ 
    results.push(data.d.results); 
} 
... 
$.when(XHR).then(function(){ 
    // Here you should have all results filled in 
    console.log(results); 
}); 
-1

而不是使用完成回調你需要設置成功回調。 docs表示成功回調具有數據參數,並且完成回調在成功和錯誤回調之後執行。

的樣本,我從我的代碼有:(該ApplyUpdate函數被調用,然後將其應用到我的現有對象JSON數據)

function doRefresh(repeat) { 
    if (nextTimeOut) clearTimeout(nextTimeOut); 
    j$.ajax({ 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     url: baseUrl + "/WebService/Service.asmx/GetSummary", 
     data: "{}", 
     dataType: "json", 
     success: function (json) { ApplyUpdate(json.d, repeat); } 
    }); 
} 

function ApplyUpdate(resp, repeat) { 
    goodObj.text(resp.GoodCount); 
    errObj.text(resp.BadCount); 
    if (repeat) nextTimeOut = setTimeout(autoRefresh, waitTime); 
} 
+0

似乎沒有改變任何東西。上面我編輯了我的問題。 – ChrisPEditor

0

你的$.when使用是不正確。 $.when未實現像Promise.all,而是它期望多個參數。幸運的是,這很容易解決。

$.when.apply($, XHR).then(... 
+0

感謝您的建議。我已經嘗試將鏈接.apply添加到$ .when中,而我所獲得的所有內容都是一個奇怪的數組,它以這個順序包含一個對象,其中包含僅來自第一個Ajax調用的數據,字符串「success」,然後是另一個promise與我無法得到的數據。 – ChrisPEditor

+0

'data'應該是一個數組或對象的數組。 –

+0

就像我說過的,'data'最終是一個數組,其中包含一個只包含ajax調用數據的_one_,一個字符串「success」和一個promise對象的數組。 – ChrisPEditor