我試過通過this question和this,但我似乎無法弄清楚如何使我的需求工作。我想在循環中多次調用https://reqres.in/api/users。此AJAX調用僅返回虛擬用戶的第一頁。在收到第一頁後,我想打電話給下一頁。以特定順序調用嵌套的AJAX調用
這裏是我的代碼:
$(document).ready(function() {
function getMoreUsers() {
var def = $.Deferred();
var requests = [];
for (var j=2; j<=4; j++) {
console.log("getting info for page # " + j);
requests.push(
$.ajax("https://reqres.in/api/users?page=" + j).done(function() {
console.log("got info for page # " + j);
def.resolve();
})
);
}
return def.promise();
}
function getAllUsers() {
var def = $.Deferred();
var requests = [];
for (var i=0; i< 2; i++) {
console.log("iteration # " + i);
requests.push(
$.ajax("https://reqres.in/api/users").done(function(data) {
console.log("got first page info");
getMoreUsers();
def.resolve();
})
);
}
return def.promise();
}
getAllUsers().done(function() {
console.log("all completed");
});
});
,我得到的輸出是這樣的:
iteration # 0
iteration # 1
got first page info
getting info for page # 2
getting info for page # 3
getting info for page # 4
all completed
got first page info
getting info for page # 2
getting info for page # 3
getting info for page # 4
got info for page # 5
不過,我想這樣的:
iteration # 0
got first page info
getting info for page # 2
got info for page # 2
getting info for page # 3
got info for page # 3
getting info for page # 4
got info for page # 4
iteration # 1
got first page info
getting info for page # 2
got info for page # 2
getting info for page # 3
got info for page # 3
getting info for page # 4
got info for page # 4
all completed
我甚至不知道如何page # 5
當我循環到4時出現在輸出中,它出現了6次,如下所示:
jQuery.Deferred()是你需要的 –
我已經使用過它,但不正確,我猜。 –
首先,您不需要創建新的延遲對象,解析併爲每個AJAX請求返回它。 '$ .ajax'方法本身返回一個延遲對象:) – Terry