[英]Wait for AJAX to finish before proceeding with the loop?
為什么每當我將ajax放入for循環中時,它都無法很好地同步?
例如,我的代碼是:
function addToUserGroupList() {
_root.qDomId('js-assignGroupArrBtn').disabled = true
for (var i = 0; i < selectedIds.length; i++) {
$.ajax({
type: "POST",
url: 'groupManage.ashx',
dataType: 'text',
data: 'type=getInfo&groupId=' + selectedIds[i],
success: function (result) {
if (result != '') {
this.groupName = result.split('&')[0];
this.groupNotes = result.split('&')[2];
userGroupList.push({ 'uid': parseInt(selectedIds[i]),
'name': this.groupName,
'adminStr': this.groupNotes
});
_root.userListObj.gourpInst.gourpTB(userGroupList);
}
},
error: function (XMLHttpRequest, status, errorThrown) {
alert('failed to add to user\'s group.');
}
});
}
_root.qDomId('js-assignGroupArrBtn').disabled = false;
selectedIds = [];
}
為什么會調出selectedIds = [];
首先在Ajax查詢之前? 是否有可能在繼續進行selectedIds = [];
之前讓ajax查詢完成selectedIds = [];
? 因為它在完成填充之前就清除了數組。 :/
首先,您確實需要了解Ajax調用是如何異步的(這就是Ajax中的“ A”所代表的意思)。 這意味着調用$.ajax()
僅啟動ajax調用(它將請求發送到服務器),其余代碼愉快地繼續運行。 有時,在其余代碼執行完畢之后,當響應從服務器返回時,將調用成功或錯誤回調處理程序。 這不是順序編程,必須采用不同的方法。
#1的意思是,在ajax調用之后,任何您想發生的事情都必須在成功或錯誤處理程序中,或者從那里進行。 位於ajax調用之后的代碼將在ajax調用完成之前運行很長時間。
因此,有多種方法來構造代碼以與該異步概念一起使用。 如果您一次只希望一次異步ajax調用,則必須進行此重組,並且不能使用簡單的for
循環。 相反,您可以創建一個索引變量,然后在完成函數中增加索引並開始下一次迭代。 這是一種編碼方式:
function addToUserGroupList() {
_root.qDomId('js-assignGroupArrBtn').disabled = true
var i = 0;
function next() {
if (i < selectIds.length) {
$.ajax({
type: "POST",
url: 'groupManage.ashx',
dataType: 'text',
data: 'type=getInfo&groupId=' + selectedIds[i],
success: function (result) {
i++;
if (result != '') {
this.groupName = result.split('&')[0];
this.groupNotes = result.split('&')[2];
userGroupList.push({ 'uid': parseInt(selectedIds[i]),
'name': this.groupName,
'adminStr': this.groupNotes
});
_root.userListObj.gourpInst.gourpTB(userGroupList);
}
next();
},
error: function (XMLHttpRequest, status, errorThrown) {
alert('failed to add to user\'s group.');
}
});
} else {
// last one done
_root.qDomId('js-assignGroupArrBtn').disabled = false;
selectedIds = [];
}
}
// kick off the first one
next();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.