2015-11-30 222 views
2

我想在多个Ajax调用完成时触发一个函数。 经过一番研究,我找到了jquery $ .when函数。 我测试过这个功能,但它不起作用。 有人知道如何解决这个问题吗?多个Ajax调用后执行函数

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调用获取的对象。

有人看到它出错了吗?

回答

1

您不应该尝试在.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); 
} 
+1

返回的函数必须延迟功能或承诺兼容返回值。决议必须解决还是拒绝。 – wajatimur

+0

@wajatimur jQuery的'$ .ajax()'函数返回一个由jQuery自动解析或拒绝的promise。 – dave