我正在使用jQuery的$.post调用,它返回一个带引号的字符串。这些引号是由json_encode行添加的。如何防止添加引号?我在$.post调用中漏掉了什么吗?
$.post("getSale.php", function(data) {
console.log('data = '+data); // is showing the data with double quotes
}, 'json');
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');
{"name":"sam"}"
中的 "name",那么(假设你有一个 JSON 对象而不是一个 JSON 数组)你可以使用 data.name
来获取,无论双引号是否存在。header('Content-type: application/json');
来指定返回JSON。 - Matthew Flaschen
dataType: 'json'
,jQuery仍然会为你解析它。 - Matthew Flaschen