如何修复发出 AJAX 请求时的'JSON Parse Error: unexpected identifier array'



我正在设置联系表单验证,我需要来自php脚本"sendEmail.php"的变量$msg。实际的邮件系统正在工作,脚本正在从索引接收表单输入.php并且正在工作(成功发送电子邮件(... 问题是"成功:函数(数据("不起作用,并且已经有几天试图弄清楚我做错了什么

我尝试更改为 $.post 函数,比较了很多类似的例子,使用"错误:"函数进行调试......

错误显示在控制台"控制台.log(错误抛出("上

我正在使用 Safari,我从 sendEmail 的 XHRs 文件夹中获取此内容.php: 输出:

array(3) {
["name"]=>
string(12) "asfasfasfasf"
["email"]=>
string(9) "asfasfasf"
["message"]=>
string(0) ""
}
{"code":404,"msg":"Please fill in all fields"}
// AJAX Call
$.ajax({
type: "POST",
url: "php/sendEmail.php",
dataType: "json",
data: {
name: name,
email: email,
message: message
},
success: function(data) {
if (data.code == '200') {
$('.alert-success').html(data.msg);
$('.alert-success').css('display', 'block');
} else {
$('.alert-danger').html(data.msg);
$('.alert-danger').css('display', 'block');
}
},error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
// Error Message
$msg = '';
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
var_dump($_POST);
// Verifications
if (!empty($name) && !empty($email) && !empty($message)) {
// Name Check
if (strlen($name) <= 4 || strlen($name) >= 30) {
$msg = 'Please type a name between 4 and 30 characters';
} else {
// Email Check
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = 'Please provide a valid email';
} else {
// Message Check
if (strlen($message) < 10) {
$msg = 'Please provide a message superior to 10           characters';
} else {
// Send Email
$msg = 'Email was sent successfully...';
echo json_encode(['code' => 200, 'msg' => $msg]);
exit;
} catch (Exception $e) {
$msg = 'Error: Email was not sent...';
}
}
}
}
} else {
$msg = 'Please fill in all fields';
}
}
echo json_encode(['code' => 404, 'msg' => $msg]);
``

检查您的代码和以下内容后:

array(3) {
["name"]=>
string(12) "asfasfasfasf"
["email"]=>
string(9) "asfasfasf"
["message"]=>
string(0) ""
}
{"code":404,"msg":"Please fill in all fields"}

我意识到此时您的代码中有一个var_dump:

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
var_dump($_POST); // <---- Remove this and everything should be okay

希望它

最新更新