2

如果用户单击前进/后退按钮时出现未完成的 AJAX 调用,我将使用以下代码中止() 。中止调用一切都很好,但之后对该函数的未来调用将不起作用。当我在中止后尝试调用 swapContent() 时,它什么也不做。中止后如何再次调用 AJAX 函数?

全球的

var ajax;

AJAX

function swapContent() {

    ajax = $.ajax({
        type: 'GET',
        data: params,
        url: 'content.php',

        success: function(data) {
            $('#browser').html(data);
        },

        error:function(e){
          // Error
        }
    });
}

onPopstate

$(window).on('popstate', function() {

    // Abort active requests
    if(ajax && ajax.readystate != 4){
        ajax.abort();
    }

});
4

2 回答 2

0

将ajax设置回null:

$(window).on('popstate', function() {
    if(ajax && ajax.readystate != 4){
        ajax.abort();
        ajax = null;
    }
});
于 2016-04-26T21:17:22.740 回答
0

看起来这行得通....

全球的

var ajax;

AJAX

function swapContent() {

    ajax = $.ajax({
        type: 'GET',
        data: params,
        url: 'content.php',

        // -- VERIFY AJAX IS NULL -- //

        beforeSend : function()    {           
                    if(ajax != null) {
                        ajax.abort(); // ABORT IF NOT NULL
                    }
        },

        success: function(data) {
            $('#browser').html(data);
            ajax = null; // NULL AJAX ON SUCCESS
        },

        error:function(e){
          // Error
        }
    });
}

onPopstate

$(window).on('popstate', function() {
    if(ajax && ajax.readystate != 4){
        ajax.abort();
        ajax = null; // NULL AFTER ABORT
    }
});
于 2016-04-26T22:01:08.737 回答