javascript - jquery 等待 $.each 完成

标签 javascript jquery ajax

您好,我有一个大问题困扰了我很长一段时间,大多数时候我都能避免它,但现在别无选择。下面是一个函数,当执行时,它会为每个选中的框发送一个 post 请求。我需要它等到 $.each 完成刷新页面。我已经在每个和每个外部的回调中使用 location.reload 执行了测试。在 10 个选定的框中,只有 7-8 个在 $.each 的回调中重新加载,如果移动到 $.each 之后(仍在 .click 中),则有 3-4 个被处理。我需要它以某种方式等待 $.each 完成然后刷新页面。有办法吗?

$('button.moveToTable').click(function(event){
            $("input:checked").each(function(){
                $.post('/table/move-to-table',
                {orderID: $(this).val(),
                    tableID: $('#moveToTableID').val()
                },
                function(data){
                    location.reload();
                });
            });
            //location.reload();
        });

最佳答案

一种简单的方法是在全局范围内存储元素的数量并减去它们。当最后一个元素完成请求时,它将重新加载。请注意,如果某些请求返回错误,这将失败,您必须处理错误事件以及减去 window.Remaining。两次或多次点击也可能破坏此方法。

window.Remaining = 0;
$('button.moveToTable').click(function(event){
    window.Remaining = $("input:checked").length;
    $("input:checked").each(function(){
        $.post('/table/move-to-table',
        {orderID: $(this).val(),
            tableID: $('#moveToTableID').val()
        },
        function(data){
            --window.Remaining;
            if (window.Remaining == 0)
                window.location.reload();
        });
    });
    //location.reload();
});

关于javascript - jquery 等待 $.each 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3928790/

相关文章:

jquery - 将 ASP.NET MVC 验证与 jquery ajax 一起使用?

javascript - JS : Processing form as a POST but retrieving as a GET?

jquery - JSON ajax SyntaxError : JSON. 解析:意外字符

javascript - 为什么这个函数不返回任何值?

Javascript - 如何突出显示最后单击的列表项

javascript - 带列表的嵌套 Promise

javascript - Highcharts JS : Gap between X-Axis labels is too thin

c# - 在表格单元格中显示按钮悬停/鼠标悬停

javascript - 将文本框与 onclick 事件的响应绑定(bind) - jquery

javascript - jQuery:$.trim() input.val() 中单词之间的空格