jQuery:计算.each()中Ajax调用成功的次数 [英] jQuery: count number of successes of ajax calls inside .each()

查看:359
本文介绍了jQuery:计算.each()中Ajax调用成功的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算对列表中每个项目成功执行jQuery ajax调用的次数.

I need to count how many times a jQuery ajax call is successfully executed on each item in a list.

我是从这里开始的,但是后来意识到,由于ajax的异步"部分,此方法将无法工作:

I started here, but then realized this won't work because of the "asynchronous" part of ajax:

var numSuccessfullUpdates = 0;

$('#saveMyListItems').click(function (event) {
    event.preventDefault();

    $('ul#myList li').each(function () {
        $.ajax({
            url: '[my_url]',
            type: "POST",
            data: {
                // [data block here, not relevant to question]
            },
            success: function () {
                numSuccessfullUpdates++;
            }
        });
    });
    if (successfullUpdates > 0){
        alert(numSuccessfullUpdates);
    }
});

有什么建议吗?

推荐答案

您可以对AJAX使用complete处理程序,并对状态结果进行计数,直到结果总数等于请求总数.这是示例代码也可以作为jsFiddle

You could use the complete handler for AJAX and count the status results until the total of results equals to the total of requests. Here is example code, also available as a jsFiddle

$('#saveMyListItems').click(function (event) {
    event.preventDefault();

    var ajaxCounter = {
        goal: $('ul#myList li').length,
        total: 0,
        success: 0,
        notmodified: 0,
        error: 0,
        timeout: 0,
        abort: 0,
        parsererror: 0
    }

    $('ul#myList li').each(function () {
        $.ajax({
            url: '/echo/html',
            type: "POST",
            timeout: 1500,
            data: {
                html: "foobar",
                delay: Math.floor(Math.random() * 5)
            },
            complete: function (jqXHR, textStatus) {
                ajaxCounter.total++
                ajaxCounter[textStatus]++;
                if (ajaxCounter.total >= ajaxCounter.goal) {
                    alert(ajaxCounter.success + ' out of ' + ajaxCounter.total);
                }
            },
        });
    });
});

这篇关于jQuery:计算.each()中Ajax调用成功的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆