我有一個注冊表,在data.errorPHP 輸出為 JSON 錯誤
exit('{"error": "Passwords do not match!"}');
注冊成功后,用戶將被重定向到 exit('{"location": "home.php"}');
我希望將 json 輸出而不是純文本放入 html css 進行樣式設定,
因此我可以為錯誤設定 div 樣式
document
.querySelector(".register form")
.addEventListener("submit", async (e) => {
e.preventDefault();
const form = e.target;
const body = new FormData(form);
const res = await fetch(form.action, {
method: "POST",
body,
});
const data = await res.json();
if (data.error) { // If there is an error
document.querySelector("#msg").innerHTML = data.error;
}
else if (data.location) { // If we want to redirect the user somewhere
window.location.href = "./" data.location;
}
});
如果我添加一個類,
<div id="msg" ></div>則不會輸出任何內容,
而只有行內樣式style="background-color:red;">會起作用
.error {
background: #F2DEDE;
color: #A94442;
border-radius: 4px;
font-weight: bold;
text-align: center;
}

我一直在研究這個 12 個小時,我看過一些關于JSON.stringify和其他的例子,
但我不知道如何將它實作到我的代碼中
uj5u.com熱心網友回復:
好吧,我仍然不知道我是否正確理解您的情況。您可以在回傳錯誤時向元素 msg 添加一個類。
if (data.error) { // If there is an error
document.querySelector("#msg").classList.add("error"); //This will be styled from your CSS. Add a background, etc
document.querySelector("#msg").innerHTML = data.error;
}
CSS:
.error {
color: white;
font-size: 14px;
margin-top: 10px;
background-color: red;
}
uj5u.com熱心網友回復:
function login($username, $password) {
// do a login
// if any errors
header('Content-Type: application/json');
echo json_encode($response);
exit;
// or if you're using any framework/controller then return properly
// using a json response containing the error i.e. "Invalid Login"
}
你想做類似服務器端的事情。然后在客戶端你想要得到回應,檢查是否有錯誤并顯示錯誤是否存在。為此使用可見類或其他東西,以便您可以更改可見性和顯示錯誤。因此,您可以按照自己想要的方式創建 div 和 css 并display: none在其上使用,然后如果確實出現錯誤,則將其設定為可見。
不要使用 PHP 生成 HTML/CSS,尤其不要以這種方式,除非您使用了正確的視圖引擎,否則最終會造成混亂。發回正確的 JSON 回應,并根據該回應在客戶端執行 UI 操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351449.html
標籤:javascript php 查询 json 阿贾克斯
上一篇:Svg按鈕路徑影片
