javascript 使用 pushState() / onpopstate 时页面不会通过“返回”重新加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7888711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Page not reloading via 'back' when using pushState() / onpopstate
提问by David Gard
I am refreshing some pages with AJAX and so an updating the history with the following code -
我正在使用 AJAX 刷新一些页面,因此使用以下代码更新历史记录 -
/** Update the page history */
var pushState_object = {
ajax_string: ajax_string,
security: security,
};
window.history.pushState(pushState_object, title, permalink);
I am then calling this onPopState function on page load -
然后我在页面加载时调用这个 onPopState 函数 -
window.onpopstate = function(e){
if(window.history.state !== null){
initiate_load_updated_page(window.history.state.ajax_string, window.history.state.security, 0)
}
}
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.
虽然从通过 AJAX 生成内容的页面到以通常方式加载的页面时使用后退按钮,但我遇到了一个小问题。URL 将更改,但页面不会重新加载。如我所料,再次单击后退会将我带到之前的页面,然后继续前进工作正常 - 这只是后退按钮不起作用的一种情况。
Any suggestions here would be appreciated.
任何建议在这里将不胜感激。
采纳答案by pimvdb
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
可用的属性,因为您没有.pushState
用来添加此类数据(它是按照您描述的正常方式加载的)。
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/.
但是,您知道的是,如果没有.state
,则它必须是原始状态,因此您可以使用这样的else
块:http: //jsfiddle.net/pimvdb/CCgDn/1/。
Lastly, you can use e.state
.
最后,您可以使用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
}
}