【发布时间】:2018-09-20 21:06:03
【问题描述】:
我想在 PHP 验证期间使用 ajax 以便 fadeIn 加载器并从中返回值以显示视觉效果消息,然后在完成时使用 fadeOut 加载器。但是我没有设法从.done function 中的 PHP 验证中获得简单的返回。
谁能帮帮我?
索引
<form action="php/valid.php" method="post" id="contact-form">
<input id="name-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="name" placeholder="Name"><br>
<input id="email-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="email" placeholder="Email"><br>
<textarea id="message-contact" class="uk-input uk-textarea uk-width-1-1 uk-margin-small" name="message" placeholder="Message" style="height:200px"></textarea>
<button id="contact-btn" class="uk-margin-small uk-button uk-button-secondary uk-width-1-1" type="submit" name="contact-form">Send</button>
</form>
JS
$(function() {
var data = {
name: $('#name-contact').val(),
email: $('#email-contact').val(),
message: $('#message-contact').val()
};
$('#contact-form').on('submit', function(event) {
$.ajax({
url: 'php/valid.php',
type: 'POST',
dataType: 'json',
data: data
})
.done(function(data) {
if (data.status == 'success') {
console.log('Success !');
} else if (data.status == 'error') {
console.log('Error !');
}
})
.fail(function(error) {
console.log(error);
});
});
});
PHP 文件
<?
header('Content-Type: application/json');
$error = false;
$regex_name = '#^[\w\s\p{L}-]{2,30}$#iu';
$regex_message = '#^[\s\S]{3,800}$#i';
if (isset($_POST['contact-form'])) {
$name = $_POST['name'];
$from = $_POST['email'];
$message = nl2br($_POST['message']);
if (!empty($name) && !empty($from) && !empty($message)) {
if (preg_match($regex_name, $name) && filter_var($from, FILTER_VALIDATE_EMAIL) && preg_match($regex_message, $message)) {
$error = array('type' => 'success');
} else {
$error = array('type' => 'error', 'value' => 'There are some errors, please check your informations.');
}
} else {
$error = array('type' => 'error', 'value' => 'Some fields are empty, please check your informations.');
}
}
if (isset($error['type']) && $error['type'] == 'success') {
$return_status['status'] = 'success';
echo json_encode($return_status);
}
else {
if (isset($error['type']) && $error['type'] == 'error') {
$return_status['status'] = 'error';
echo json_encode($return_status);
}
}
?>
谢谢。
【问题讨论】:
-
那么当你运行你的代码时会发生什么?检查控制台是否有错误?在
done()回调的顶部完成了console.log(data);?此外,您应该在执行 ajax 请求之前添加一个event.preventDefault()(在单击事件的回调中),否则它只会定期向页面发送帖子,而您的 ajax 代码将永远不会运行。 -
顺便说一句,
data变量将在页面加载时设置。您可能应该将其移动到点击事件中,否则所有值将始终为空。 -
@MagnusEriksson l 更改代码作为第一个答案,但仍然有对象错误:Object { readyState: 4, getResponseHeader: ......
-
readyState: 4仅表示请求已完成,并没有告诉我们任何其他信息。如果你在fail()-callback 中得到了它,那么打开浏览器开发工具并转到“网络”-选项卡。发出请求并检查请求的外观以及服务器返回的内容(响应)。 -
我还建议使用根文件夹中的相对 url。如果文件夹
php位于您的Web 根目录中,您可以通过以斜杠开头的url 来做到这一点:url: '/php/valid.php',。如果不是,只需添加来自网络根目录的完整路径:url: '/path/to/php/valid.php',
标签: php ajax validation