Javascript 如何在不重新加载的情况下动态更改 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11932869/
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
How to dynamically change URL without reloading?
提问by Dr.Kameleon
OK, this what I'm trying to do (I think Google mostly does this as well) :
好的,这就是我想要做的(我认为谷歌也主要这样做):
Scenario A :
情景A:
In page /Main_Page
let's say there are 3 sections. When user clicks on section A "link", section A
's content is loaded through AJAX and embedded into the page.
在页面中,/Main_Page
假设有 3 个部分。当用户点击 A 部分的“链接”时,section A
的内容通过 AJAX 加载并嵌入到页面中。
Scenario B :
情景B:
When /Main_Page/Section_A
is loaded, we practically go to the very same page (as in scenario A) - /Main_Page
and load Section A
via AJAX - as before.
当/Main_Page/Section_A
被加载时,我们实际上去非常相同的页面(如在方案A) -/Main_Page
和负载Section A
通过AJAX -如前。
The problem :
问题 :
We've got 2 identical resulting pages, but the URL is different (in the first case it'll be just /Main_Page
, while in the second it will be /Main_Page/Section_A
).
我们有 2 个相同的结果页面,但 URL 不同(在第一种情况下它只是/Main_Page
,而在第二种情况下它将是/Main_Page/Section_A
)。
What I want to do :
我想做的事 :
- In Scenario A, after loading
Section A
via AJAX, how should I do it so that the appearing URL (in the browser address bar) is/Main_Page/Section_A
(or anything else for that matter), without any sort of redirecting, page reloading, etc?
- 在场景 A 中,
Section A
通过 AJAX加载后,我应该怎么做才能使出现的 URL(在浏览器地址栏中)是/Main_Page/Section_A
(或其他任何内容),而不需要任何类型的重定向、页面重新加载等?
回答by Adi
Your problem can be solved by implementing the History API, especially by using the pushState()
method. I recommend reading about it in MDN. There's also an all-in-one solution called History.js, it will help you implement it x-browser easily (It will fallback to URL hashes #
if the browser doesn't support it).
您的问题可以通过实现History API来解决,尤其是通过使用该pushState()
方法。我建议在 MDN 中阅读它。还有一个名为History.js的一体化解决方案,它将帮助您轻松实现 x-browser(#
如果浏览器不支持它,它将回退到 URL 哈希)。
Here's an example:
下面是一个例子:
history.pushState('', 'New Page Title', newHREF);
Not excited enough? Here's a demothat will encourage you to implement it.
不够激动?这是一个演示,将鼓励您实施它。
回答by Pavan Mehta
I just found a tutorial and it worked for me,
我刚刚找到了一个教程,它对我有用,
$('a').click(function(){
var value = $(this).attr('id');
window.location.hash = value; // it appends id to url without refresh
});
$(window).bind('hashchange' function() {
var newhash = window.location.hash.substring(1) // it gets id of clicked element
// use load function of jquery to do the necessary...
});
i got the above code from http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/
我从http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/得到了上面的代码