[英]Execute function after multiple ajax calls
我想在多個 ajax 調用完成時觸發一個函數。 經過一番研究,我找到了 jquery $.when 函數。 我測試了這個功能,但它不起作用。 有誰知道如何解決這個問題?
var root = 'http://jsonplaceholder.typicode.com';
$(function(){
restCall.ajaxcalls();
})
var restCall =
{
ajaxcalls: function(){
$.when(this.getAlbums(), this.getPhotos()).done(function(fetchedAlbums,fetchedPhotos){
console.log(fetchedAlbums);
console.log(fetchedPhotos);
});
},
getAlbums:function() {
$.ajax({
type: 'GET',
url: root + '/albums'
}).done(function(response){
return response;
}).fail(this.ajaxFail);
},
getPhotos: function(){
$.ajax({
type: 'GET',
url: root + '/photos'
}).done(function(response){
return response;
}).fail(this.ajaxFail);
},
ajaxFail: function(xhr,message,error){
console.log("het liep mis met de ajax call",xhr,message,error);
}
};
控制台日志返回未定義,但我想要由 ajax 調用獲取的對象。
有人看到哪里出錯了嗎?
你永遠不應該嘗試在.done()
處理程序中返回一個值,因為它是一個異步調用。 相反,返回由您的 ajax 調用返回的承諾,並在該結果上使用您的$.when()
,如下所示:
getAlbums: function() {
return $.ajax({
type: 'GET',
url: root + '/albums'
}).fail(this.ajaxFail);
},
getPhotos: function(){
return $.ajax({
type: 'GET',
url: root + '/photos'
}).fail(this.ajaxFail);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.