我有一個注冊表單,成功后用戶被重定向到 home.php(有效)
但所有在 PHP 中回顯的“警報/錯誤”,在提交后,將重定向到 register.php 并在空白頁面中顯示錯誤。
(我如何將它們顯示到<div >位置?)
<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
基于此,請提供正確的代碼片段以將其標記為已解決。
uj5u.com熱心網友回復:
如果您總是從 PHP 回傳 JSON,而不是有時也從 HTML 回傳,這可能會讓您的生活更輕松。
例如,在檢查頂部的錯誤時register.php,您應該回傳 JSON 物件 --- 例如
{error: "Email is not valid!"}
而不是他們的 HTML equivilents。
這意味著在您的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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350013.html
標籤:javascript php
