【发布时间】:2014-06-16 06:41:13
【问题描述】:
我不熟悉将 jQuery 与 AJAX 结合使用。我想构建一个简单的表单,当其中一个字段输入不正确时提示用户。
我唯一的要求(目前)是名字必须是“John”。
html (ajaxtutorial.html)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Form</title>
</head>
<body>
<form action="ajax/contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<input type="submit" value="Send">
<div>
</form>
<script src="js/jquery-1.11.0.js"></script>
<script src="js/main.js"></script>
</body>
</html>
jQuery (main.js):
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), //references the inputs within the find function
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
dataType: 'json',
cache: false,
success: function(result) {
if(result.error == true) {
console.log('Did not type John');
}
else {
console.log('Typed John');
}
}
});
return false;
});
php (contact.php):
<?php
$errors = array();
$form_data = array();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if ($name != 'John') {
$errors['name'] = true;
}
if (array_key_exists('name',$errors)) {
$form_data['success'] = true;
$form_data['error'] = true;
} elseif (empty($errors)) {
$form_data['success'] = true;
}
echo json_encode($form_data);
?>
我觉得很简单,但是解决不了。我想通过它的类(即结果。['class'])来识别错误,以便为每个错误提供独特的反馈。
感谢您的帮助
【问题讨论】:
-
你确定你发送到你的 php 脚本的数据存在吗?此外,您可以将 $(this).serialize() 放入 ajax 请求块中,而不是您正在执行的每个循环
-
您是否检查过您的网络选项卡以查看 PHP 返回的响应?
标签: php jquery ajax forms error-handling