Javascript Popstate事件阻止Ajax请求

时间:2015-10-11 17:06:17

标签: javascript jquery

我遇到了关于在Popstate事件上阻止ajax请求的问题。

所以,这是我的代码:

$(window).on('popstate', function(e) {
        var state = e.originalEvent.state;
            if (state !== null) {


    loadProducts(location.pathname);
        }

});

function loadProducts(url) {

    $.ajax({
            type        : "GET", 
            url         : url, 
            dataType    : "html",
            cache       : true,
            success     : function(checks) {
                            $(".ajaxpage").html(checks);
                    }
            });
}; 

$('#product').on("click", ".paging a", function(e) {
    e.preventDefault();
    history.pushState(null, null, $(this).attr('href')); 
    loadProducts($(this).attr('href'));
});

pushstate事件非常适合ajax请求。但当我点击"后退按钮"该页面将再次执行相同的ajax请求。这是为什么?我不再需要ajax因为我已经访问过该页面了吗?就像Github一样?

如何防止popstate事件上的ajax请求?

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

此行错误

var state = e.originalEvent.state

您应该通过编写

来访问该州
var state = e.state

供参考,https://developer.mozilla.org/en-US/docs/Web/Events/popstate

相关问题