$.ajax错误不会从php显示
我不熟悉将jQuery与AJAX结合使用。我想构建一个简单的表单,当其中一个字段输入不正确时提示用户 我(目前)唯一的要求是名字必须是“约翰” html(ajaxtutorial.html) php(contact.php):$.ajax错误不会从php显示,php,jquery,ajax,forms,error-handling,Php,Jquery,Ajax,Forms,Error Handling,我不熟悉将jQuery与AJAX结合使用。我想构建一个简单的表单,当其中一个字段输入不正确时提示用户 我(目前)唯一的要求是名字必须是“约翰” html(ajaxtutorial.html) php(contact.php): 我觉得很简单,但解决不了。我想通过错误的类别(即结果。['class'])来识别错误,以便为每个错误提供唯一的反馈 感谢您的帮助尝试使用,而不是像这样循环 $('form.ajax').on('submit', function() { var that =
我觉得很简单,但解决不了。我想通过错误的类别(即结果。['class'])来识别错误,以便为每个错误提供唯一的反馈
感谢您的帮助尝试使用,而不是像这样循环
$('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);
您确定要发送到php脚本的数据存在吗。另外,您可以在ajax请求块中放入$(this).serialize(),而不是您正在执行的每个循环。您是否检查了网络选项卡以查看PHP返回的响应?感谢您让我知道serialize()快捷方式!
<?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);
?>
$('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;
});
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);