返回到前一个页面时显示前一个页面中ajax获取的数据

来源:互联网 发布:图片动态特效制作软件 编辑:程序博客网 时间:2024/06/11 03:13

      情景实现:项目有个任务就是在订单结算提交前可以增加发票抬头,用的是AJAX请求后台后返回数据展示在前端页面,添加完同时选取该发票后提交订单,如果因为各类原因(比如余额不足,库存不够)的影响订单提交不成功,用户想返回上一页修改订单重新下单结算时,发现刚才新增的发票数据不见了,ajax获取并插入页面的结构都没有了,而实际上数据是存在的。

      解决方案:网上查询后发现可以通过处理history对象来解决。可以用history.pushState方法和history.replaceState以及window对象的popstate事件,这个方式可以让你用JS自己控制URL和前进后退事件,并且用ajax刷新网页的局部内容。

     使用了history.replaceState方法来改变当前页面的state,每次ajax获取信息后,将页面中希望保留的内容放入state中,当返回到这个页面中时,读取state中的信息,如果state不为null,那么将state中的页面结构展示出来。

这里写图片描述

步骤很简单,大概分两步:

1、ajax获取信息并拼装到html结构后,将希望保留的html结构放入state中

  var stateObj = { current_html:  $('#for_add_newInv').html() ,invoice_all: $('#invoice_control').html()};  history.replaceState(stateObj, '', 'flow.php?step=checkout');

2、返回这个页面的时候,查看state是否保存有信息,如果有就展示出来,再做一些对应的处理就好了

<script type="text/javascript">  var prev_html = history.state && history.state.current_html;  if (prev_html) {    $('#for_add_newInv').html(prev_html);  }  var invoice_all = history.state && history.state.invoice_all;  if (invoice_all) {    $('#invoice_control').html(invoice_all);  }  </script >

     关于pushstate跟replaceState方法的理解和案例:http://www.cnblogs.com/micotan/p/5887460.html
http://www.zhangxinxu.com/wordpress/2013/06/html5-history-api-pushstate-replacestate-ajax/

阅读全文
0 0
原创粉丝点击