jQuery $.post和json_encode返回带引号的字符串

8

我正在使用jQuery的$.post调用,它返回一个带引号的字符串。这些引号是由json_encode行添加的。如何防止添加引号?我在$.post调用中漏掉了什么吗?

$.post("getSale.php", function(data) {
    console.log('data = '+data); // is showing the data with double quotes
}, 'json');
2个回答

13

json_encode() 返回一个字符串。根据json_encode() 的文档:

Returns a string containing the JSON representation of value.
你需要在 data 上调用 JSON.parse(),这将解析 JSON 字符串并将其转换为对象:
$.post("getSale.php", function(data) {
    data = JSON.parse(data);
    console.log('data = '+data); // is showing the data with double quotes
}, 'json');
然而,由于您在console.log()调用中将字符串data =data连接起来,所以记录的将是data.toString(),它将返回对象的字符串表示形式,即[object Object]。因此,您需要单独记录data 在另一个console.log()调用中。可以像这样实现:
$.post("getSale.php", function(data) {
    data = JSON.parse(data);
    console.log('data = '); // is showing the data with double quotes
    console.log(data);
}, 'json');

1
在任何最近版本的jQuery中,如果您使用正确的MIME类型,它将自动解析JSON。 - Matthew Flaschen
@Matthew +1,我理解了这一点,因为它仍然是一个字符串返回,我假设 MIME 类型是错误的。 - Alex
@Alex,在这种情况下,你也可以手动指定dataType: 'json',jQuery仍然会为你解析它。 - Matthew Flaschen
是的,它起作用了。我在$.post调用末尾确实有'json'。这不就相当于指定了dataType吗? - Catfish
JSON.parse在ie7中会引发错误。我该如何解决它? - Catfish
显示剩余2条评论

1
你想用接收到的数据做什么?如果你只是想获取 JSON 消息中的特定键,比如在 "{"name":"sam"}" 中的 "name",那么(假设你有一个 JSON 对象而不是一个 JSON 数组)你可以使用 data.name 来获取,无论双引号是否存在。

我正在尝试在获取数据后将其插入到HTML标签中。 - Catfish
我在我的php文件中使用json_encode(array())来返回值,这样做有问题吗? - Catfish
1
@Catfish,你还应该使用header('Content-type: application/json');来指定返回JSON。 - Matthew Flaschen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接