有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
当前回答
在HTML5之前,我们可以使用:
parent.location.hash = "hello";
and:
window.location.replace("http:www.example.com");
此方法将重新加载页面,但HTML5引入了不应重新加载页面的history.pushState(page,caption,replace_url)。
其他回答
parent.location.hash = "hello";
位置的任何更改(window.location或document.location)都将导致对新URL的请求,如果您不仅仅是更改URL片段。如果更改URL,则更改URL。
如果您不喜欢当前使用的URL,请使用服务器端URL重写技术,如Apache的mod_rewrite。
HTML5引入了history.pushState()和history.replaceState()方法,分别允许您添加和修改历史条目。
window.history.pushState('page2', 'Title', '/page2.php');
从这里了解更多信息
您可以在应用程序的任何位置使用这个美丽而简单的功能。
function changeurl(url, title) {
var new_url = '/' + url;
window.history.pushState('data', title, new_url);
}
您不仅可以编辑URL,还可以同时更新标题。
这现在可以在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;
}
};
有关操纵浏览器历史的更深入了解,请参阅MDN文章。