gpt4 book ai didi

javascript - Ajax - 为什么在 $.post() 中使用 JSON.parse(data) 和 dataType

转载 作者:行者123 更新时间:2023-11-29 17:42:28 25 4
gpt4 key购买 nike

我使用 ajax 动态填充数据表。

代码如下:

Javascript:

  $.post("/import_data.php", {add: new_row}, "json").done(function(data){
data = JSON.parse(data);

if (data[0] === 'example_1') {
.....
$("#error_1").modal("show");
}
else if (data[0] === 'example_2') {
.....
$("#error_2").modal("show");
}
else {
table.row.add(data).order([0, 'desc']).draw();
}
});

PHP(导入数据.php):

 ...    
$arr = array('info1', 'info2', 'info3', 'info4');
echo json_encode($arr);

但有些事情我不明白,为什么我必须使用 JSON.parse (data) 这行,这不是 dataType 的工作还是我的代码有问题?

我怎样才能改进我的脚本?

编辑:

Console.log(data) -- 在 JSON.parse(data) 之前:

["super","1","220","example"]

在 JSON.parse(data) 之后:

(4) ["super", "1", "220", "example"]
0: "super"
1: "1"
2: "220"
3: "example"
length: 4
__proto__: Array(0)

如果我不放 JSON.parse(data)他没有带我 super 元素,而是带我 [

最佳答案

当您依赖 dataType 参数时,我很震惊地发现数据在传递给 done 回调时没有被解析(我已经在本地复制了您的问题) 在你的例子中。这是因为如果要包含 dataType 参数,jQuery 的 $.post 要求您为 success 参数传递参数;见Aditya Sharma's answer来自 docs 的报价

无论如何,您不应该依赖 dataType 参数;相反,您的 PHP 应该返回正确的 Content-Type header :

<!-- language: lang-php -->
<?php
header("Content-Type: application/json");
$arr = array('info1', 'info2', 'info3', 'info4');
echo json_encode($arr);

如果您这样做,您的 $.post 调用就可以正常工作(没有 JSON.parse 调用)。

如果由于某种原因您不能这样做,请使用成功回调而不是 done(或将 null 作为 success 参数传递并继续使用 .done);由于 "json" 参数,jQuery 将为您解析 JSON:

<!-- language: lang-js -->
$.post("temp.php", {add: new_row}, function(data) {
// ...
}, "json");

// or
$.post("temp.php", {add: new_row}, null, "json").done(function(data) {
// ...
}, "json");

...然后,再次不需要调用 JSON.parse

但同样,如果 PHP 正确识别响应的类型会更好。

关于javascript - Ajax - 为什么在 $.post() 中使用 JSON.parse(data) 和 dataType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52310265/

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