利用AJAX和history.replaceState无刷新的改变页面URL
在以往我们需要改变URL的参数时,我会通过修改
最近我的项目中由于一个基础库的bug(短时间内还没办法去修改(〃>皿<))必须通过修改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){
if (history.state){
var state = e.state;
//do something(state.url, state.title);
}
}, false);
window.history.pushState(state, document.title, url);
这样就可以结合 ajax
和 pushState
完美的进行无刷新浏览了。一些注意点
无论是history.pushStat
还是 history.replaceState
,其URL必须是同一域名下的,跨域是万万做不到的。
state
对象虽然可以存储很多自定义的属性,但对于不可序列化的对象则不能存储,如:DOM对象。
Casino Roll
回复删除What you need 승인전화없는 사이트 to know before you play at the netteller casino. 카 심바 At Casino Roll, our casino team strives to create a fresh and exciting experience betting for players. This 바카라 배팅전략 is the chance to have