(一)HTML5 - pushState 無重新整理更新地址

來源:互聯網
上載者:User

標籤:

可以解決什麼問題:

可以實現網頁的ajax載入,同時又能完成URL的改變而沒有網頁跳轉重新整理的跡象,就像是改變了網頁的hash(#)一樣。

優於hash:

避免了改變hash的問題,避免了使用者不理解URL的形式感到疑惑,同時還有onpopstate提供監聽,良好響應後退前進。而且它不需要這個URL真實存在。

HTML5 的 pushState+Ajax:

pushState() 的基本參數是:

1 var state = ( {2 url: ~href, title: ~title, ~additionalKEY: ~additionalVALUE3 } );4 window.history.pushState(state, ~title, ~href);5 window.history.replaceState( state, ~title, ~href);    // 替換
pushState、replaceState 的區別

pushState()可以建立曆史,可以配合popstate事件,而replaceState()則是替換掉當前的URL,不會產生曆史。

註:

只能用同域的URL替換,例如你不能用http://baidu.com去替換http://google.com。

state對象不儲存不可序列化的對象如DOM。

pushState 配合 popstate 監聽
1 window.addEventListener(‘popstate‘, function(evt){2     var state = evt.state;3     var tilte = state.tilte ;4     var url = state.url5     document.title=title;6     doSomething(url);  // 自訂函數7 }, false);
popstate與hashChange

對於http://www.abc.com/path?search=ghj#hashstring 這個url來說,

① http://為協議
② www.abc.com為host
③ path為path,也就是我們的子目錄,每個子目錄可以幹很多事情
④ #hashstring為hash相關

①-③頁面會重新整理,④頁面不重新整理,

pushState與改變hash 相同點:可以改變url地址

pushState與改變hash 不同點:hashChange只能改變hashstring 部分,pushState可改變①-③而不重新整理頁面

popstate 為1-3環節的變化引起的回調
hashChange 為hash變化引起的回調,是不同的

 

(一)HTML5 - pushState 無重新整理更新地址

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.