1. 程式人生 > >終止當前頁面所有還在請求中的AJAX請求

終止當前頁面所有還在請求中的AJAX請求

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $.xhrPool = [];
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.xhrPool.indexOf(jqXHR);
        if
(index > -1) { $.xhrPool.splice(index, 1); } } }); // Everything below this is only for the jsFiddle demo $('#cancelBtn').click(function() { $.xhrPool.abortAll(); }); $('#doneLbl').hide(); $.mockjax({ url: "/OneSecond", responseTime: 1000 }); $.mockjax({ url: "/ThreeSecond"
, responseTime: 3000 }); $.mockjax({ url: "/FiveSecond", responseTime: 5000 }); $.mockjax({ url: "/SevenSecond", responseTime: 7000 }); $.ajax({ url: '/OneSecond', success: function() { $('#completedList').append('<li>1 second finished</li>'); }, error: function
() {
$('#canceledList').append('<li>1 second canceled</li>'); } }); $.ajax({ url: '/ThreeSecond', success: function() { $('#completedList').append('<li>3 second finished</li>'); }, error: function () { $('#canceledList').append('<li>3 second canceled</li>'); } }); $.ajax({ url: '/FiveSecond', success: function() { $('#completedList').append('<li>5 second finished</li>'); }, error: function () { $('#canceledList').append('<li>5 second canceled</li>'); } }); $.ajax({ url: '/SevenSecond', success: function() { $('#completedList').append('<li>7 second finished</li>'); $('#doneLbl').show(); }, error: function () { $('#canceledList').append('<li>7 second canceled</li>'); $('#doneLbl').show(); } });