HTML5:触发popstate时刷新页面 [英] HTML5: Refresh page when popstate is fired
问题描述
我有一个类似的ajax搜索表单:
I have a ajax search-form like:
url:/ search /
url: /search/
=>用户输入搜索字词并点击按钮
=> User enters a search-term and clicks a button
=>搜索已完成并通过页面div中的ajax显示结果
=> search is done and shows the results via ajax in a div on the page
但是:我还希望用户能够将URL复制并粘贴给朋友并浏览之前的搜索。因此,当触发搜索时,我将浏览器地址栏中的URL更改为
But: I also want the user to be able to copy&paste the URL to friends and navigate through the previous searches. So when triggering the search, I change the url in the browsers addressbar from
/ search /
/search/
到
/ search /?q = yourkeyword
/search/?q=yourkeyword
使用:
window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);
这会将浏览器地址栏中的网址更改为/ search /?q = yourkeywords并正常工作。
This changes the url in the browsers addressbar to /search/?q=yourkeywords and works fine.
现在,点击后退按钮,浏览器地址栏再次显示/ search /,这很好。但页面内容未重新加载,它仍会显示/ search /?q = yourkeyword的结果。
Now, hitting the back-button, the browsers addressbar is showing again /search/, which is fine. But the page-content is not reloaded, it still shows the results from /search/?q=yourkeyword.
所以我添加了:
window.addEventListener("popstate", function(e)
{ location.reload();
});
这是正确的方法吗?它在FF和Chrome等桌面浏览器中运行良好,但是在iOS中,popstate事件是在/ search /上首次加载searchform时触发的,导致该页面无法重新加载。
Is this the correct way? It works fine in desktop-browsers like FF and Chrome, but for example in iOS, the popstate-event is fired on the very first loading of searchform on /search/, resulting in a neverending reloading of that page.
什么是正确的方法?
推荐答案
最简单的解决方案是设置一个使用 pushState
时的全局变量。然后,在onpopstate处理程序中,检查是否已设置。例如:
The simplest solution is to set a global variable when you use pushState
. Then, in your onpopstate handler just check if that is set. E.g.:
window.historyInitiated = true;
window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);
...
window.addEventListener("popstate", function(e) {
if (window.historyInitiated) {
window.location.reload();
}
});
这篇关于HTML5:触发popstate时刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!