gpt4 book ai didi

javascript - 通过ajax根据php返回设置样式

转载 作者:行者123 更新时间:2023-12-01 02:00:12 24 4
gpt4 key购买 nike

我的 AJAX 返回不是 css 样式错误。

我发现 PHP 的所有返回都显示为 success 属性函数。我的所有返回都显示为 successCSS(Bootstrap)。

我不确定是否有更好的方法从我的 PHP 接收数据,然后相应地设置输出样式。

<a class="btn btn-primary" onclick="validateForm()">Send</a>
<div class="alert hide" role="alert hide">
<div class="status" id="status"></div>
</div>
function validateForm() {

$.ajax({
url: "register.php",
type: "POST",
data: $('#registration-form').serialize(),
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message).addClass('successCSS');
if (data.code) //If mail was sent successfully, reset the form.
$('#registration-form').closest('form').find("input[type=text],
textarea ").val("
");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR).addClass('errorCSS');
}
});
}
<?php
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];

header('Content-Type: application/json');
if ($firstname === '')
{
print json_encode(array(
'message' => 'firstname cannot be empty',
'code' => 0
));
exit();
}
if ($surname === '')
{
print json_encode(array(
'message' => 'Surname cannot be empty',
'code' => 0
));
exit();
}
if ($email === '')
{
print json_encode(array(
'message' => 'Email cannot be empty',
'code' => 0
));
exit();
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
print json_encode(array(
'message' => 'Email format invalid.',
'code' => 0
));
exit();
}
}
$content = "Email: $email \nMessage: $message";
$recipient = "@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array(
'message' => 'Registration successful !',
'code' => 1
));
exit();

最佳答案

您需要在进行 ajax 调用之前检查 code === 0 和 code === 1 并重置类名称,这样您最终就不会添加太多类。试试这个

function validateForm() {


$('#status').text('').removeClass('successCSS').removeClass('errorCSS');
$.ajax({
url: "register.php",
type: "POST",
data: $('#registration-form').serialize(),
success: function(data, textStatus, jqXHR) {
if(data.code && data.code === 1) {
$('#status').text(data.message).addClass('successCSS');
} else {
$('#status').text(data.message).addClass('errorCSS');
}

if (data.code) //If mail was sent successfully, reset the form.
$('#registration-form').closest('form').find("input[type=text],
textarea ").val("
");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text('error when submitting form ' + textStatus + ' : ' + errorThrown).addClass('errorCSS');
}
});
}

关于javascript - 通过ajax根据php返回设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com