[英]previous HTML won't render with back button after history.pushState()
我有下面的 HTML,它从GET /home
提供,并使用 Javascript 劫持表单提交事件,以便将方法从 POST 更改为 DELETE。 服务器侦听对DELETE /delete
的请求,它实际上返回一个 303 重定向到GET /new
,它服务于一些 HTML。 The Javascript updates the address bar to example.com/new
using the history API, and renders the HTML using using window.document.documentElement.innerHTML = text
. 这一切都可以找到,当我单击后退按钮时,地址栏确实会更改回之前的地址(example.com/home),但不会呈现 HTML。 为什么是这样? 我已经阅读了Mozilla 文档,但我找不到任何关于不渲染 HTML 的信息,如果后退按钮更新地址栏,页面应该更新为 URL? 我也尝试过使用history.replaceState()
但它没有用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/delete" method="POST">
<input type="submit" value="submit" />
<input name="key" value="val" />
</form>
</body>
<script>
const form = document.querySelector("form");
form.addEventListener("submit", async e => {
e.preventDefault();
console.log(new URLSearchParams(new FormData(e.currentTarget)));
const response = await fetch(form.action, {
body: new URLSearchParams(new FormData(e.currentTarget)),
method: "DELETE",
redirect: "follow",
});
const text = await response.text();
history.pushState({}, "", response.url);
// history.replaceState({}, "", response.url);
window.document.documentElement.innerHTML = text;
});
</script>
</html>
根据您的代码,您将替换包含脚本部分的 innerHTML。 请将您的脚本移动到 head 标签(如果可能的话),或者替换整个文档的 innerHTML,创建一个父 div 并替换该 div 的内容。
所以代替这个 -
window.document.documentElement.innerHTML = text;
做这个 -
documemt.getElementById('SomeDIV').innerHTML = text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.