是否可以在不刷新页面的情况下更改浏览器的地址栏? [英] Is there a way to change the browser's address bar without refreshing the page?
问题描述
我正在开发一个网络应用程序。在其中,我有一个名为类别的部分,每当用户单击一个类别时,更新面板就会加载适当的内容。
I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.
用户单击类别后,我想将浏览器的地址栏网址从
After the user clicked the category I want to change the browser's address bar url from
www.mysite.com/products
类似
www.mysite.com/products/{selectedCat}
而无需刷新页面。
我可以使用某种JavaScript API来实现此功能吗?
without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?
推荐答案
使用HTML5,您无需重新加载即可修改网址:
With HTML5 you can modify the url without reloading:
如果您想在浏览器的历史记录中发布新帖子(例如,后退按钮)会起作用)
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');
如果您只是想更改URL而无法返回
If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');
该对象可用于ajax导航:
The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');
window.onpopstate = function (e) {
var id = e.state.id;
load_item(id);
};
在此处了解更多信息: http://www.w3.org/TR/html5-author/history.html
Read more here: http://www.w3.org/TR/html5-author/history.html
一个后备解决方案: https://github.com/browserstate/history.js
这篇关于是否可以在不刷新页面的情况下更改浏览器的地址栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!