【问题标题】:Execute function after multiple ajax calls多次ajax调用后执行函数
【发布时间】:2015-11-30 20:43:18
【问题描述】:

我想在多个 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 调用获取的对象。

有人知道哪里出错了吗?

【问题讨论】:

    标签: javascript jquery ajax rest .when


    【解决方案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);
    }
    

    【讨论】:

    • 返回的函数必须是延迟函数或承诺兼容的返回值。必须解决或拒绝解决的地方。
    • @wajatimur jQuery 的$.ajax() 函数返回一个被 jQuery 自动解析或拒绝的承诺。
    猜你喜欢
    • 2015-09-26
    • 2012-10-19
    • 2020-01-31
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多