window.history.pushState與ajax實現無刷新更新頁面url

ajax能無刷新更新數據,可是不能更新urlhtml

 

HTML5的新API: window.history.pushState, window.history.replaceStateajax

用戶操做history,點擊前進後退按鈕會觸發popstate事件。瀏覽器

這些方法能夠協同window.onpopstate事件一塊兒工做。url

 

改變url的demospa

本頁是foo.html,url改變成bar.html,內容卻不變code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
        <button onclick="changeUrl()">按鈕</button>
        
        <script>
        function changeUrl() {
            var stateObj = {foo: 'bar'};
            window.history.pushState(stateObj, 'page 2', 'bar.html'); // 這將讓瀏覽器的地址欄顯示http://mozilla.org/bar.html,但不會加載bar.html頁面也不會檢查bar.html是否存在。
        }
            
        </script>
    </body>
</html>
相關文章
相關標籤/搜索