小编典典

如何在不重新加载页面的情况下修改URL?

html

有没有办法可以在不重新加载页面的情况下修改当前页面的URL?

如果可能,我想访问#哈希 之前 的部分。

我只需要更改域 的部分,所以就好像我没有违反跨域策略一样。

 window.location.href = "www.mysite.com/page2.php";  // Sadly this reloads

阅读 601

收藏
2020-05-10

共1个答案

小编典典

现在,可以在Chrome,Safari,Firefox 4+和Internet Explorer 10pp4 +中完成此操作!

例:

 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;
    }
};
2020-05-10