回答

收藏

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

技术问答 技术问答 271 人阅读 | 0 人回复 | 2023-09-12

有没有办法在不重新加载页面的情况下修改当前页面的 URL?
( e; [' a1 ^; }+ |: u如果可能的话,我想去# hash前一部分。* S4 q3 Q2 N; E9 q
我只需要更改域之后因此,我不违反跨域战略。) K% e2 y' r/ @) ^6 Z: f  f- J5 H
    window.location.href = "www.mysite.com/page2.php";  // Sadly this reloads
    ' M: [6 O3 |+ r+ D
               ) E- m  l6 y$ e' t3 `. ?; f3 u! i
    解决方案:                                                               
* d& s1 m" r% t* T# b( i+ R                                                                现在可以在 Chrome、Safari、Firefox 4  和 Internet Explorer 10pp4  中完成!2 m! n. Q3 D- }7 b3 D2 P6 `
例子:/ c3 o+ C- e. P0 B+ B0 U
    function processAjaxData(response,urlPath){     document.getElementById("content").innerHTML = response.html;     document.title = response.pageTitle;     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"",urlPath); }( }# M. ^+ z7 O5 g4 r1 z
然后,你可以用它window.onpopstate检测后退/前进按钮导航:
( |0 p8 c; \/ i$ [7 T& P4 r6 Y. b[code]window.onpopstate = function(e){    if(e.state){          document.getElementById("content").innerHTML = e.state.html;        document.title = e.state.pageTitle;   }code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则