我认为您正在寻找 history.pushState url,它允许您进行部分页面加载,并且在使用和不使用 javascript 的情况下具有相同的 url。
比如你的base url是http://site.com/
withhistory.pushState,你可以用javascript修改页面为javascript.htm
,这样url就变成了http://site.com/javascript.htm
。
#!
url 仅适用于 javascript,因为无法在服务器端访问 #fragment。使用 hashbangs,您的 url 将类似于http://site.com/#javascript.htm
注意,这!
是不必要的。由于您可以在哈希之后设置任何内容,因此您也可以拥有 url http://site.com/#!/javascript.htm
。
不幸的是,由于 IE 不支持 history.pushState,因此您必须将#!
url 作为后备。
这两种方法都不会破坏后退按钮,但必须为每种方法设置不同的方式。
Hashbangs 的工作方式如下:
function change(){
//page update logic
}
//hashchange event binding
(typeof window.addeventListener === "function")
? window.addEventListener("hashchange", change, false)
: window.attachEvent("onhashchange", change);
//This is how the hash is set
location.hash = "hashstring";
//Accessing it returns the hashstring, with a #
location.hash; //returns #hashstring
History.pushState 有点复杂,因为您将页面的“状态”存储在一个对象中。
以下是有关此方法的一些很好的参考:
这两种方法都需要 javascript 页面操作。我有一个这类网址的例子。http://timshomepage.net/comic/有一系列不同网络漫画的链接,并将它们嵌入到页面的 iframe 中。禁用 javascript 后,链接将类似于http://timshomepage.net/comic/dilbert。使用 history.pushState,我可以拥有相同的 url。使用 hashbang 后备,我得到一个这样的网址:http ://timshomepage.net/comic/#!/dilbert