我不熟悉在AJAX中使用jQuery。我想构建一个简单的表单,在其中一个字段输入不正确时提示用户。
我唯一的要求(目前)是名称必须是“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']),以便为每个错误提供唯一的反馈。
感谢您的帮助
答案 0 :(得分:0)
尝试使用serialize()代替循环,
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method');
$.ajax({
url: url,
type: type,
data: that.serialize(),// use form.serialize() here
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中分配success
和error
,并尝试使用
if (array_key_exists('name',$errors)) {
// remove success key from here
$form_data['error'] = true;// only error
} elseif (empty($errors)) {
$form_data['success'] = true; // only success
}
echo json_encode($form_data);