History配合Ajax实现无刷新页面跳转

一些网站头尾内容都是一样的,刷新总显得浪费。从体验上讲,点击导航,右侧Ajax局部刷新是更优的策略。

Ajax局部刷新小菜,稍有经验都能轻松应对。现在如果提出如下需求:每次ajax刷新就如果页面刷新一样,可以后退查看之前内容,怎么破?

我的策略如下:

每次手动点击左侧的菜单,我将Ajax地址的查询内容(?后面的)附在demo HTML页面地址后面,使用history.pushState塞到浏览器历史中。
浏览器的前进与后退,会触发window.onpopstate事件,通过绑定popstate事件,就可以根据当前URL地址中的查询内容让对应的菜单执行Ajax载入,实现Ajax的前进与后退效果。
页面首次载入的时候,如果没有查询地址、或查询地址不匹配,则使用第一个菜单的Ajax地址的查询内容,并使用history.replaceState更改当前的浏览器历史,然后触发Ajax操作。

1. history.pushState
菊花插一刀之意,用法举例:
history.pushState({}, “页面标题”, “xxx.html”);

2. history.replaceState
换把菊花刀之意,用法举例:
history.replaceState(null, “页面标题”, “xxx.html”);

3. window.onpopstate
在菊花刀拔插的时候……,用法举例:
window.addEventListener(“popstate”, function() {
var currentState = history.state;
/*
* 该干嘛干嘛
*/
});

案例:http://www.zhangxinxu.com/study/201306/ajax-page-html5-history-api.html?area=songjiang

http://www.zhangxinxu.com/wordpress/2013/06/html5-history-api-pushstate-replacestate-ajax/

猜你喜欢

转载自blog.csdn.net/weixin_40821790/article/details/78684721