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

有没有一种方法可以修改当前页面的 URL 而无需重新加载页面?

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

我只需要更改域之后的部分,所以我并不违反跨域政策。

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

最佳答案

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

有关更多信息,请参阅此问题的答案: Updating address bar with new URL without hash or reloading the page

例子:

 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;
    }
};

要更深入地了解操纵浏览器历史记录,请参阅 this MDN article .

https://stackoverflow.com/questions/824349/

相关文章:

html - 如何使浏览器窗口的 div 高度为 100%?

。使用哪个?">html -