jquery - 在 .when() 中使用延迟对象时,如何使用 .when().then() 触发函数?

标签 jquery ajax jquery-deferred

我有一个页面,其中有数量可变的 AJAX 调用,这些调用是在常见事件上触发的。 AJAX 调用本身是为了更新 SQL 数据库中的相关字段。所有调用完成后,我想刷新页面,以便它现在反射(reflect)刚刚所做的更改。

到目前为止,我在这里使用了以下问题/答案。 jQuery when each is completed, trigger function

这是迄今为止我的代码:

var team_update = function(e) {
    var $items = $('.sortable-items');
    var XHRs = [];

    $items.each(function(){
        var team_id = $( this ).attr("id");
        var data =  {
            tid: team_id,
            users: $('#' + team_id).sortable('toArray')
            };

        XHRs.push(
            $.ajax({ 
                type: "POST", 
                url: "update.php", 
                data: data, 
                complete: function(data){
                } 
            })  
        );

    });

    $.when(XHRs).then(function(){
        console.log('Refreshing Screen');
        $('#content-wrapper').load( 'index.php' );
    });

}

我期望发生的是,一旦我的所有 ajax() 请求完成, $('#content-wrapper').load( 'index.php' ); 将触发完全的。不过,似乎正在发生的情况是,一旦所有请求发送完毕,回调就会触发,而不一定是在它们完成之后,所以有时我的页面更新仍然包含“旧”数据。

下图在顶部显示了我的初始页面加载,可以忽略。接下来的 4 个条目显示了该问题。有 3 个 POST 请求,这是我更新数据库的 3 个 ajax 调用,最后一个 GET 是页面刷新。页面刷新 GET 在发送所有 3 个 ajax 调用后触发,但它不会等到最后一个 ajax 调用完成才触发。因此,它会在前一个 ajac 调用完成更新数据库之前获取旧数据。

Firebug timeline

我在这里做错了什么?

最佳答案

我最近应用了类似的东西。

when() 需要一个延迟对象或延迟对象列表,但如果您想使用数组,则需要使用 apply()

替换

$.when(XHRs)

$.when.apply(null, XHRs)

如果这不起作用,您可能需要将 Ajax 调用包装在函数中:

function SendAjax(data){
return $.ajax({Options as they are in your ajax call});
}

然后将它们推送到 XHR,如下所示:

XHRs.push(SendAjax(data));

以下是我在代码中实现此功能的方法,您可以根据需要进行调整:

//We want to notify how many memberships have been made after they're all made. since they're async, we'll need to use promises
//however, because we repeat the same ajax call with different parameters, we need to push them to an array and then apply() them.
checkedBoxes.each(function () {
    createArray.push(CreateMembershipsAjax(this));
});
//we did the work before we start creating them, so show some progress;
add1ToProgress();
$.when.apply(null, createArray).done(function () {
    //this function will only start once all ajax calls have been successfull.
    divCreated.append(membershipCount + " memberships created:");
    MembershipsCreated = true;
    window.close();
});

...

CreateMembershipsAjax(element){
    //process element, create Data from it;
    return $.ajax({option});
}

是的,这些注释实际上在我的代码中,而不仅仅是为了在此页面上进行澄清而添加的。

关于jquery - 在 .when() 中使用延迟对象时,如何使用 .when().then() 触发函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24306790/

相关文章:

javascript - React中ajax后计数

ruby-on-rails - 充当可投票的 Ajax 失败

javascript - 将变量列表动态包含到 Jquery 函数中作为参数

jquery - jQuery-jsonp插件和延迟的对象,不延迟

javascript - 对象索引并使用 youtube api 接下来播放

jquery - jquery 中元素名称的动态选择

javascript - 使用 jquery 或 javascript 上传 1 GB 的文件

javascript - 使用 Angular 将数据绑定(bind)到 div 中的单个单词

c# - 单击链接按钮时显示面板

javascript - 来自单个请求的 ajax 请求数组