【问题标题】:Jquery deferred issue (ajax then animation then callback)Jquery 延迟问题(ajax 然后动画然后回调)
【发布时间】:2014-09-05 13:13:48
【问题描述】:

我必须进行 AJAX 调用,然后做一些事情,并在一切完成后成为回调。

我调用 getUsers() 函数,需要知道该函数内的所有步骤何时完成。

我尝试的任何方法都不起作用......

function getUsers(userId){
    var dfd = $.Deferred();
    $.ajax({
        type: "GET",
        url: "../getUsers.php",
        data: {userid: userId},
        success: function(output){
            output = JSON.parse(output);
            $(output.activeUsers).appendTo("#users");
            $(output.inactiveUsers).appendTo("#users_inactive");

            $('.user').each(function(index){
                $(this).animate({
                    'height':55+'px'
                })
            })
            $('.user').promise().done(function() {
                overlay.fadeOut('fast',function(){
                    dfd.resolve;
                    return dfd.promise();
                });
            });
        }
    })
}


$.when(
    getUsers()
).then(function(){
    alert('something')
})

我做错了什么

【问题讨论】:

  • complete: 用于$.ajax()。这将在请求完成时触发。请求是成功还是失败都没有关系。
  • getUsers 中缺少return
  • 阿伦,我需要回调的地方有return,还是应该在最后? / Spokey,我需要回调不是在 ajax 之后,而是在所有东西之后......
  • @Sobakinet not...那是来自回调方法...您需要在getUsers 底部添加`return dfd.promise();`
  • dfd.resolve(); - 你需要调用解析函数

标签: jquery callback deferred


【解决方案1】:

在 cmets 中指出了多个问题

function getUsers(userId) {
    var dfd = $.Deferred();
    $.ajax({
        type: "GET",
        url: "../getUsers.php",
        data: {
            userid: userId
        },
        success: function (output) {
            output = JSON.parse(output);
            $(output.activeUsers).appendTo("#users");
            $(output.inactiveUsers).appendTo("#users_inactive");

            $('.user').animate({
                'height': 55 + 'px'
            }).promise().done(function () {
                overlay.fadeOut('fast', function () {
                    //need to invoke the resolve function
                    dfd.resolve();
                });
            });
        }
    }).fail(function () {
        //need to reject the promise if ajax request fails
        dfd.reject();
    });
    //return the promise here
    return dfd.promise();
}


$.when(getUsers()).then(function () {
    alert('something')
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    相关资源
    最近更新 更多