Javascript:如何在不刷新页面的情况下更改地址栏中的 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7869223/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:34:53  来源:igfitidea点击:

Javascript: How do I change the URL in the address bar without refreshing the page?

javascriptajaxweb-applications

提问by Leo Jiang

Possible Duplicate:
How do I, with JavaScript, change the URL in the browser without loading the new page?

可能的重复:
如何使用 JavaScript 在不加载新页面的情况下更改浏览器中的 URL?

I noticed that web apps like GMail and GrooveShark can change the URL in the address bar of my browser without refreshing the page. Ajax is obviously used to change the content. How can I change the URL?

我注意到像 GMail 和 GrooveShark 这样的网络应用程序可以在不刷新页面的情况下更改浏览器地址栏中的 URL。Ajax 显然是用来改变内容的。如何更改网址?

回答by topek

Gmail and Grooveshark only change the hash, this is done by changing:

Gmail 和 Grooveshark 只更改哈希,这是通过更改:

location.hash = 'blah'

If you target HTML5 enabled browsers, you can use window.history.pushState and window.history.popState, see http://spoiledmilk.dk/blog/html5-changing-the-browser-url-without-refreshing-page

如果您的目标是支持 HTML5 的浏览器,您可以使用 window.history.pushState 和 window.history.popState,请参阅http://spoiledmilk.dk/blog/html5-changed-the-browser-url-without-refreshing-page

回答by Nick Clark

You may want to look into HTML5 push state. I know iQuery Mobile is using this feature to modify the location URL without triggering a page load and it might be the right solution for you.

您可能想要查看 HTML5 推送状态。我知道 iQuery Mobile 正在使用此功能来修改位置 URL,而不会触发页面加载,它可能是适合您的解决方案。

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Here is an example of how it works:

以下是它如何工作的示例:

window.history.pushState(data, "Title", "/new-url");