如何在不重新加载页面的情况下修改 URL? [英] How do I modify the URL without reloading the page?

查看:32
本文介绍了如何在不重新加载页面的情况下修改 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way I can modify the URL of the current page without reloading the page?

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

I would like to access the portion before the # hash if possible.

我只需要更改域之后的部分,所以这不像我违反了跨域策略.

I only need to change the portion after the domain, so it's not like I'm violating cross-domain policies.

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

推荐答案

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

This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!

有关更多信息,请参阅此问题的答案:用新的地址栏更新没有散​​列或重新加载页面的 URL

See this question's answer for more information: 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 来检测后退/前进按钮导航:

You can then use window.onpopstate to detect the back/forward button navigation:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

<小时>

要更深入地了解操纵浏览器历史记录,请参阅 这篇 MDN 文章.

这篇关于如何在不重新加载页面的情况下修改 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆