javascript - 发出 AJAX 请求时如何修复“JSON 解析错误:意外的标识符数组”
问题描述
我正在设置联系表单验证,我需要来自 php 脚本“sendEmail.php”的变量 $msg。实际的邮件系统正在运行,脚本正在接收来自 index.php 的表单输入并且正在运行(成功发送电子邮件)......问题是“成功:函数(数据)”不起作用,并且一直是一对几天试图弄清楚我做错了什么
我尝试更改为 $.post 函数,比较了很多类似的示例,使用 'error:' 函数进行调试...
错误显示在控制台“console.log(errorThrown)”上
我正在使用 Safari,我从 sendEmail.php 的 XHRs 文件夹中得到这个: 输出:
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
希望它有帮助
推荐阅读
- r - 是否可以在 geom_bar 中使用孵化
- web-scraping - 在网站中绕过 CAPTCHA 以使用“Java”进行网络抓取
- mysql - SQL将日期从一种格式转换为另一种格式
- regex - 如何在 linux 命令中使用正则表达式获取文件中唯一单词的输出?
- php - PHP图像上传 - 几个错误
- python - 通过调用嵌套字典中的键和值 tru 输入来获取键
- django - 芹菜 Django 身体编码
- html - 如何镜像 MOSS 抄袭检测的结果?
- python - 在 KivyMD 中使用 ScreenManager 时如何在主文件的 kv 文件中引用 id
- sql-server - 如何在现有数据库 ASP.NET Core MVC 和 EF Core(DB-First)中使用 Identity