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

2024-05-15 02:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果可能的话,我想访问散列之前的部分。

我只需要在域之后更改部分,所以这不像是违反跨域策略。

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

Tags: 方法comurlwww情况location页面window
3条回答

现在可以在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

HTML5引入了^{}^{}方法,这些方法允许您分别添加和修改历史记录条目。

window.history.pushState('page2', 'Title', '/page2.php');

here了解更多有关此的信息

如果要更改url但不想将条目添加到浏览器历史记录中,也可以使用HTML5replaceState

if (window.history.replaceState) {
   //prevents browser from storing history with each change:
   window.history.replaceState(statedata, title, url);
}

这将“破坏”后退按钮功能。在某些情况下,这可能是必需的,例如图像库(您希望“上一步”按钮返回到库索引页,而不是在查看的每个图像中向后移动),同时为每个图像提供自己的唯一url。

相关问题 更多 >

    热门问题