Javascript 无需重新加载现有页面即可更改浏览器地址栏中的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10953792/
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
Change URL in browser address bar without reload existing page
提问by Radley Sustaire
Possible Duplicate:
Modify the URL without reloading the page
可能的重复:
修改 URL 而不重新加载页面
I'm looking for a way to make my internal links functional using my current javascript animations, without causing the page to reload when you click on them - but I would like the URL to update in the browser.
我正在寻找一种方法来使用我当前的 javascript 动画使我的内部链接正常工作,而不会在您单击它们时导致页面重新加载 -但我希望 URL 在浏览器中更新。
Many websites do this, here is a good example: http://grooveshark.com/#!/search?q=adf
许多网站都这样做,这里有一个很好的例子:http: //grooveshark.com/#!/search?q=adf
How do they get the URL to update without the page reloading?
他们如何在不重新加载页面的情况下更新 URL?
More details:
更多细节:
Currently a link on my page looks like <a href="#aboutus">About Us</a>
, this takes you to <div id="aboutus"></div>
via javascript.
目前我页面上的一个链接看起来像<a href="#aboutus">About Us</a>
,这会带你<div id="aboutus"></div>
通过 javascript。
The javascript looks something like:
javascript 看起来像:
$("#navigation a").click(function(e){
animate(..scroll to section..);
e.preventDefault(); // <==========
});
I believe the "e.preventDefault()" is what is causing the URL to not be updated, but how do I prevent the browser from reloading the page when the URL is changed?
我相信“e.preventDefault()”是导致 URL 未更新的原因,但是如何在 URL 更改时防止浏览器重新加载页面?
How do other websites do it? What is this method called (so I can further research it)?
其他网站是怎么做的?这种方法叫什么(所以我可以进一步研究它)?
thanks.
谢谢。
采纳答案by Maziar Aboualizadehbehbahani
Here is an example:
下面是一个例子:
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState(
{
"html":response.html,
"pageTitle":response.pageTitle
},
"",
urlPath
);
}
回答by Charlie Kilian
It looks to me like the whole thing is done with AJAX. The #!
in the URL is causing the browser to interpret the remainder of the URL as an anchor -- anchors don't cause page reloads (in fact, the server will never see what anchor the browser is on in the course of a normal HTTP request). When the URL changes, Javascript takes over, inspects the querystring, and loads whatever is appropriate from the server using web services.
在我看来,整个事情都是用 AJAX 完成的。将#!
在URL中导致浏览器解释URL的剩余部分作为一个锚-锚不会导致页面重新加载(事实上,服务器永远不会看到浏览器是在一个正常的HTTP请求的过程中有什么锚)。当 URL 发生变化时,Javascript 会接管,检查查询字符串,并使用 Web 服务从服务器加载适当的内容。
I haven't looked at it too much in depth, but that is what it looks like to me.
我没有深入研究它,但这就是我的样子。