我有一個javascript函數,它進入一個循環併爲每個循環發出異步ajax調用。我需要知道所有ajax調用何時已經返回並被處理,因爲我想在那個時候更新UI。
循環如下:
function sync_SyncLocalStorageToServer() {
if (helper_IsAppOnline()) {
$.log('sync_SyncLocalStorageToServer detects app is ONLINE');
// Post each cached entry to the server - this is the main sync function
for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 8) === 'response') {
$.log('Sync found response with key=' + lskey);
var postdata = localStorage.getItem(lskey); // Get the form data
$.log('Calling server with ls response:' + postdata);
var localkey = lskey;
$.ajax({
type: "POST",
dataType: 'json',
url: "/Profile/PostForm",
data: { jsonpost: postdata },
success: function (data) {
if (data.rc == "success") {
localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry
$.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey);
} else {
$.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey);
}
}
, error: function (data) {
$.log('ERR:' + data);
}
});
}
}
}
else {
$.log('sync_SyncLocalStorageToServer detects app is OFFLINE');
}
}
什麼是我打電話給我的UI刷新功能,當最後一個異步Ajax調用已經最終從服務器返回的最簡單的方法?
謝謝。
我可以在函數頂部創建一個var,然後調整它嗎?這樣做是否會有可能的範圍或線程問題?非常感謝。 – Journeyman 2011-06-10 16:17:25
@Journeyman編輯了我的答案 – Matt 2011-06-10 16:21:25