历史回溯功能记录请求。一个页面可能会多次请求自己。因此,当按下后退按钮时,您可能会返回到同一页面的上一个请求。
这是一个非常简单的例子:
爱丽丝.html:
<h1>This is Alice</h1>
<a href="charlie.php">Go to Charlie</a>
鲍勃.html:
<h1>This is Bob</h1>
<a href="charlie.php">Go to Charlie</a>
查理.php:
<h1>This is Charlie</h1>
<p id="output">Here goes the server output</p>
<form method="post">
<input type="hidden" id="somevalue" name="somevalue" value="0">
<button type="button" onclick="window.history.go(-1);">Back</button>
<button type="submit">Calculate</button>
</form>
<script>
// Simulate some server side action
document.getElementById("output").innerHTML = document.getElementById("somevalue").value = "Value = " + Math.random();
</script>
Alice.html 和 Bob.html 都链接到 Charlie.php。 Charlie.php 有一个表单并多次调用自己,以对数据进行一些服务器操作。
历史回退功能回退一个请求,而不是一页。要返回到 Alice 或 Bob,用户必须按她隐藏计算按钮的相同次数返回按钮。
问题:如何在不考虑对查理的请求数量的情况下后退一页?
编辑:我正在寻找一个简单的“备份一页”按钮的通用解决方案,而不使用服务器端变量。
只有 HTML5 的解决方案是可以的。
最佳答案
无需浏览多个欺骗性历史记录项,您可以使用以下方法从一开始就阻止创建它们:
-
location.replace()
(这将替换当前历史项中的页面,因此无需额外点击)
但由于您的“服务器对数据的操纵”,这可能是不可能的,下面的代码可能会提供一个解决方案:
window.onload = function() {
document.getElementById("back").onclick = function() {
sessionStorage.setItem("href",location.href); //store current page into sessionStorage
history.go(-1); //go back one page
};
if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
else {sessionStorage.removeItem("href");} //clear sessionStorage
};
在下面的演示中(所以不允许 sessionStorage)我不得不模拟“浏览历史”和“为每个历史项目加载页面”,所以代码看起来有点不同,使用数组和其他变量和函数,但原理应该是一样的:
代码笔:https://codepen.io/anon/pen/OgBgGg?editors=1011 强>
jsfiddle:https://jsfiddle.net/j0ddnboq/2/
关于javascript - 如何一次返回一页(返回到引用页面,而不是它本身),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990542/