当使用pushState()/ onpopstate时,页面不会通过'back'重新加载 [英] Page not reloading via 'back' when using pushState() / onpopstate

查看:131
本文介绍了当使用pushState()/ onpopstate时,页面不会通过'back'重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用AJAX刷新了一些页面,因此用下面的代码更新了历史记录:

I am refreshing some pages with AJAX and so an updating the history with the following code -

/** Update the page history */
var pushState_object = {
    ajax_string: ajax_string,
    security: security,
};
window.history.pushState(pushState_object, title, permalink);

然后我在页面加载时调用这个onPopState函数 -

I am then calling this onPopState function on page load -

window.onpopstate = function(e){
    if(window.history.state !== null){
        initiate_load_updated_page(window.history.state.ajax_string, window.history.state.security, 0)
    }
}

当从通过AJAX生成内容的页面转到以通常方式加载的页面时,使用后退按钮时遇到了一些小问题。网址将会改变,但网页不会重新加载。按照我的预期,再次点击返回页面,然后继续前进,这只是一种后退按钮无法使用的情况。

I am having a slight problem though using the back button when going from a page where the content was generated through AJAX to a page that was loaded in the usual way. The URL will change, but the page will not reload. Clicking back again takes me to the page before, as I would expect, and then going forward works fine - it is just that one situation where the back button does not work.

这里的任何建议都将不胜感激。

Any suggestions here would be appreciated.

推荐答案

初始状态没有 .state 属性可用,因为您没有使用 .pushState 来添加这些数据(它按照您描述的正常方式加载)。

The initial state does not have a .state property available, because you didn't use .pushState to add such data (it was loaded the normal way as you describe).

但是你知道的是,如果没有 .state ,它必须是原始状态,所以你可以使用 else 像这样阻止: http:// jsfiddle。 net / pimvdb / CCgDn / 1 /

What you do know though, is that if there is no .state, it must be the original state, so you can use an else block like this: http://jsfiddle.net/pimvdb/CCgDn/1/.

最后,您可以使用 e.state

window.onpopstate = function(e){
    if(e.state !== null) { // state data available
        // load the page using state data
        initiate_load_updated_page(e.state.ajax_string, window.history.state.security, 0);

    } else { // no state data available
        // load initial page which was there at first page load
    }
}

这篇关于当使用pushState()/ onpopstate时,页面不会通过'back'重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆