前言:window.history.go()方法可加载历史列表中的某个具体的页面,例如你打开一个浏览器后,然后又连续跳转了几个页面,window.history.go(-1)就会跳转到当前页面的上一个页面,window.history.go(1)就会跳转到当前页面的下一个页面。跟浏览器自带的“后退”“前进”键一样的效果。他们的特点就是,跳转页面后浏览器不会向服务器重新提交请求,而是会从缓存记录中加载数据。其中包括ajax请求的数据。
相对应后退、前进的方法window.history.back(),window.history.forward()
一、问题重现
<?php
//server.php代码
echo (int)microtime(true) ;
<!-- demo1页面代码 -->
<body>
<a href="demo2.php">跳转到demo2页面</a>
<script>
$.get('server.php',function(res,status){
if(status){
console.log('demo1页面');
console.log(res);
}
});
</script>
</body>
<!-- demo2页面代码 -->
<body>
<a onclick="window.history.go(-1)">返回到demo1</a>
<script>
$.get('server.php',function(res,status){
if(status){
console.log('demo2页面');
console.log(res);
}
});
</script>
</body>
其中,php代码返回的当前时间的时间戳。第一个页面跟第二个页面分别对server.php进行了get请求,对象响应信息进行了输出。
打开demo1页面,查看输出。然后点击“跳转到demo2页面”按钮,跳转到demo2页面,一段时间后,点击“返回到demo1”按钮。
这时会发现 使用window.history.go(-1)返回到demo1,demo1输出的时间戳还是跟demo2的一样,说明页面对ajax请求返回的信息也进行了缓存。
二、解决方案
给请求链接后面添加随机数
<!-- demo1页面代码 -->
<body>
<a href="demo2.php">跳转到demo2页面</a>
<script>
$.get('server.php?'+Math.random(),function(res,status){
if(status){
console.log('demo1页面');
console.log(res);
}
});
</script>
</body>
<!-- demo2页面代码 -->
<body>
<a onclick="window.history.go(-1)">返回到demo1</a>
<script>
$.get('server.php?'+Math.random(),function(res,status){
if(status){
console.log('demo2页面');
console.log(res);
}
});
</script>
</body>