事件描述:
h5增加了一个事件window.onpopstate,当用户点击那两个按钮就会触 发这个事件。但是光检测到这个事件是不够的,还得能够传些参数,也就是说返回到之前那个页面的时候得知道那个页面的pageindex。通过 history的pushstate方法可以做到,pushstate(pageindex)将当前页的pageindex存起来,再返回到这个 页面时获取到这个pageindex。
window.history.pushstate描述:
window.history.pushstate(state, title, url);
state对象:是一个javascript对象,它关系到由pushstate()方法创建出来的新的history实体。用以存储关于你所要插入到历史 记录的条目的相关信息。state对象可以是任何json字符串。因为firefox会使用用户的硬盘来存取state对象,这个对象的最大存储空间为640k。如果大于这个数 值,则pushstate()方法会抛出一个异常。
title:firefox现在回忽略这个参数,虽然它可能将来会被使用上。而现在最安全的使用方式是传一个空字符串,以防止将来的修改。
url:用来传递新的history实体的url,浏览器将不会在调用pushstate()方法后加载这个url。也许会过一会尝试加载这个url。比如在用户重启了浏览器后,新的url可以不是绝对路径。如果是相对路径,那么它会相对于现有的url。新的url必须和现有的url同域,否则pushstate()将抛出异常。这个参数是选填的,如果为空,则会被置为document当前的url。
直接贴代码:
/** * created: aaron. * address: http://www.cnblogs.com/aaron-pan/ */ //var pageindex=window.history.state===null?0:window.history.state.page; (function($,window,undefined){ var loaddata={ pageindex:window.history.state===null?1:window.history.state.page, //pageindex:0, init:function(){ this.getdata(this.pageindex); this.nextpage(); }, getdata:function(pageindex){ var that=this; $.ajax({ type:'post', url:'./data/getmovices'+pageindex+'.json', datatype:'json', async:false, success:function(data){ that.renderdom(data); } }) }, renderdom:function(movies){ var bookhtml= <table>+ <tr>+ <th>电影</th>>+ <th>导演</th>+ <th>上映时间</th>+ </tr>; for(var i=0;i
运行结果:
这样就可以达到通过ajax进行交互也能实现监听前进/后台/刷新的功能了。
附浏览器兼容性:
相关推荐:
最全ajax跨域解决方案
jquery ajax局部刷新实例
ajax实时刷新处理的实现方法
以上就是实例讲解如何解决ajax不支持前进后退刷新的问题的详细内容。