ajax载入与浏览器历史的前进与后退

来源:互联网 发布:windows管道命令 编辑:程序博客网 时间:2024/06/05 18:37

ajax载入与浏览器历史的前进与后退


使用到的知识点:

  • popstate
  • history.pushState
  • history.replaceState

Ajax可以实现页面的无刷新操作——优点;但是,也会造成另外的问题,无法前进与后退!(前进后退无法重现上一次操作);

通过以下代码保存每次请求的参数即可实现浏览器后退操作;

<script>    var num = 0;    var str;    document.addEventListener("click",function()         history.pushState({num:num}, "",window.location.href);        ++num;        str = "index.html?name=" +num;        history.replaceState({"num":num}, "", str);    })    window.addEventListener("popstate", function() {        console.log(window.location.search);        alert("执行ajax请求");    });</script>
原创粉丝点击