利用AJAX和history.replaceState无刷新的改变页面URL
在以往我们需要改变URL的参数时,我会通过修改 window.location.search 来实现。但这必然会导致页面的再次刷新,这不是我们想看到的结果。 最近我的项目中由于一个基础库的bug(短时间内还没办法去修改(〃>皿<))必须通过修改url参数来实现一些功能,需要增加的参数存储在 sessionStorage.dataSearch 中,具体代码如下: if(location.search.length == 0) { if(history.replaceState) { history.replaceState(null,null,sessionStorage.dataSearch); } else { location.search = sessionStorage.dataSearch; } } 说到这个 history.replaceState 我们就不得不提 history.pushStat 和 history.replaceState 这些API了。 API的使用 pushState 是将指定的URL添加到浏览器历史里, replaceState 是将指定的URL替换当前的URL。 var state = { title: title, url: options.url, otherkey: othervalue }; window.history.pushState(state, document.title, url); 响应浏览器的前进、后退操作 window 对象上提供了 onpopstate 事件,上面传递的 state 对象会成为 event 的子对象,这样就可以拿到存储的title和URL了。 window.addEventListener('popstate', function(e){ ...