开发者

jQuery: count number of successes of ajax calls inside .each()

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

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++;
            }
        });
  开发者_Python百科  });
    if (successfullUpdates > 0){
        alert(numSuccessfullUpdates);
    }
});

Any suggestions?


You can try the new when() and then() features available in jQuery 1.5+,

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).then(myFunc, myFailure);

Here execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

So, by the above function you can check if all the ajax requests were successfully completed if the myFunc function is run.


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);
                }
            },
        });
    });
});


You need to count all responses as well, and alert when the total is reached or when a sensible timeout has expired.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜