在abop()onPopstate之后,AJAX停止工作

时间:2016-04-26 20:48:12

标签: javascript jquery ajax abort popstate

当用户点击前进/后退按钮时,如果有未完成的AJAX调用,我将使用以下代码 abort()。这一切都很好地中止了呼叫,但在此之后调用该功能将无法正常工作。当我尝试在中止后调用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();
    }

});

2 个答案:

答案 0 :(得分:0)

将ajax设置为null:

$(window).on('popstate', function() {
    if(ajax && ajax.readystate != 4){
        ajax.abort();
        ajax = null;
    }
});

答案 1 :(得分: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
    }
});