window.history.pushState与ajax实现无刷新更新页面url

ajax能无刷新更新数据,但是不能更新url

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

用户操作history,点击前进后退按钮会触发popstate事件。

这些方法可以协同window.onpopstate事件一起工作。

改变url的demo

本页是foo.html,url改变成bar.html,内容却不变

<!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>
原文地址:https://www.cnblogs.com/lqcdsns/p/6118161.html