0
$.each(emails, function(index, value) 
{
    $.post('ajax/send_email.php', { email: value, ... }, function(data)
    {
        $('#emails_sent').text('Sent ' + (index + 1) + '/' + num_emails);
    }); 
});

$(function()
{
    $('#cancel').on('click', function(e) 
    { 
        hidePopupWindow();
    });
});

$.each运行时没有任何按钮,例如取消工作——它们不能被选择或按下。

4

1 回答 1

1

您可以修改您的程序以使用维护当前存在的 xhr 请求的数组,然后在取消时中止 XHR。请看下面的代码:

var globalAbort = false,
xhrPool = [];
$.each(emails, function(index, value) {
    if (!globalAbort) {
        $.ajax("ajax/send_email.php", { 
            beforeSend: function(xhr){
                xhrPool.push(xhr);
            },
            email: value,
            success: function(data, status, xhr){
                var index = xhrPool.indexOf(xhr);
                if (index > -1) {
                    xhrPool.splice(index, 1);
                }
                $('#emails_sent').text('Sent ' + (index + 1) + '/' + num_emails);
            }
        });
    }
});
$('#cancel').on('click', function(e) { 
    var xhrLen = xhrPool.length;
    for (var i = 0; i < xhrLen; i++) {
        xhrPool[i].abort();
    }
    xhrPool.length = 0;
    hidePopupWindow();
});
于 2013-07-04T04:19:04.783 回答