我有一个注册表,对JSON的错误data.error PHP输出
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" class="error"></div>不会输出任何内容,
虽然只有内联样式的style="background-color:red;">才能工作
.error {
background: #F2DEDE;
color: #A94442;
border-radius: 4px;
font-weight: bold;
text-align: center;
}

我已经研究了12个小时了,我看到了一些关于JSON.stringify和其他的例子,
但我不知道如何在代码中实现这一点
发布于 2021-11-06 16:20:43
嗯,我还是不知道我是否正确理解了你的情况。您可以在元素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;
}发布于 2021-11-06 16:14:02
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://stackoverflow.com/questions/69865537
复制相似问题