gpt4 book ai didi

php - $ .ajax错误将不会从php显示

转载 作者:行者123 更新时间:2023-12-03 08:56:31 25 4
gpt4 key购买 nike

我是将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);
?>

我觉得这很简单,但无法解决。我想通过错误的类别(即result。['class'])来识别错误,以便为每个错误提供唯一的反馈。

谢谢您的帮助

最佳答案

尝试使用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中,如果出现错误,您将分配 successerror都尝试一下,
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错误将不会从php显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379699/

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