有没有一种方法可以修改当前页面的URL而无需重新加载页面?
如果可能,我想访问#哈希之前的部分。
我只需要更改域后的部分,所以就好像我没有违反跨域策略一样。
window.location.href = "www.mysite.com/page2.php"
现在,可以在Chrome,Safari,Firefox 4+和Internet Explorer 10pp4 +中完成此操作!
有关更多信息,请参见此问题的答案: 使用新URL更新地址栏而无需哈希或重新加载页面
例子:
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
然后,您可以window.onpopstate
用来检测后退/前进按钮的导航:
window.onpopstate = function(e){
if(e.state){
document.getElementById("content").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
本文首发于前端黑洞网,博客园同步跟新