我有一个注册表单,成功后用户将被重定向到 home.php(有效)
而且所有在 PHP 中都是回显的“警报/错误”,在提交后,将重定向到 register.php 并在空白页面中显示错误。
(如何将它们显示到 <div class="msg">
位置?)
<script>
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {accept: "application/json", // let PHP know what type of response we want},
body})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})
</script>
<body>
<div class="msg"></div> <!--position for error/ wrong pass etc-->
据此,请提供正确的代码片段,以便将其标记为已解决。
最佳答案
如果您总是从 PHP 返回 JSON,而不是有时返回 HTML,那么您的生活可能会变得更加轻松。
例如,当检查 register.php
顶部的错误时,您应该返回 JSON 对象 --- 例如
{error: "Email is not valid!"}
而不是它们的 HTML 等效项。
这意味着在您的 fetch
中,您现在始终能够获取 JSON 内容(目前,如果出现其中一条消息,您可能会在浏览器的调试控制台中收到错误)返回,因为它不是有效的 JSON)。然后,在 JavaScript 中,您可以检测到这一点并根据需要进行切换:
if (data.error) { // If there is an error
document.querySelector(".msg").textContent = data.error;
}
else if (data.location) { // If we want to redirect the user somewhere
window.location.href = "./" + data.location;
}
关于javascript - 如何在错误请求时显示警报,但在成功时重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69860645/