javascript - 检测 AJAX 调用循环何时完成

标签 javascript jquery ajax

我有一个网页,可以将无限数量的项目提交回服务器进行处理。

我决定使用 AJAX 调用 Web 服务以 25 个为一组提交这些项目。所以我的循环看起来像这样:

// Submit elements
for (var i = 0; i < ids.length; i += 25) {

    var productIds = ids.slice(i, Math.min(i + 25, ids.length - 1));

    $.post('/Services/ImportProducts.asmx/ImportProducts', JSON.stringify({ importProductIds: productIds }))
    .done(function (result, statusText, jqxhr) {

        // TODO: Update progress

    })
    .always(function () {
        // TODO: Test for error handling here
    });
}

到目前为止,这似乎是正确的。但是,当所有处理完成后,我想刷新页面。鉴于上面的代码,当最后一个 AJAX 调用完成时,我没有看到执行任务的简单方法。

由于 $.post() 是异步的,因此该循环将在 AJAX 调用之前完成。由于 AJAX 调用可能以与提交时不同的顺序完成,因此我无法简单地测试上次提交的调用何时完成。

我如何知道这段代码何时完成?

最佳答案

您可以利用 jQuery 的 promises 来做到这一点。一般工作流程包括将每个 promise 添加到一个数组中,然后使用 jQuery when 应用该数组。当所有的 promise 都返回时执行另一个回调。

这样的事情应该有效:

var promises = []
for (var i = 0; i < ids.length; i += 25) {

    var productIds = ids.slice(i, Math.min(i + 25, ids.length - 1));

    var promise = $.post('/Services/ImportProducts.asmx/ImportProducts', JSON.stringify({ importProductIds: productIds }))
    .done(function (result, statusText, jqxhr) {

        // TODO: Update progress

    })
    .always(function () {
        // TODO: Test for error handling here
    });

    promises.push(promise);
}

/*
    Note, the "apply" function allows one to unwrap an array to parameters for a
    function call. If you look at the jQuery.when signature, it expects to be 
    called like: $.when(promise1, promise2, promise3). Using .apply allows you 
    to satisfy the signature while using an array of objects instead.

    See MDN for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
*/
$.when.apply($, promises)
    .done(function() {
        console.log("All done!") // do other stuff
    }).fail(function() {
        // something went wrong here, handle it
    });

关于javascript - 检测 AJAX 调用循环何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491757/

相关文章:

javascript - jQuery addClass 现在不工作

javascript - 如何在 jQuery 中启用所有禁用行

php - 从 PHP foreach 循环获取 Ajax 变量(第二部分)

javascript - 将 Javascript 对象值转换为全局变量

javascript - 让图像淡入、下降和反弹一次到位

javascript - Jquery 扩展 div - 如何滚动到它

javascript - 将网页信息转换成pdf信息

javascript - 使用js子串选择第二个字符串点

javascript - 为什么叫长轮询

javascript - 我是否应该担心我的网站在 IE9 下崩溃以及如何修复?