jQuery $ .post和json_encode返回一个带引号的字符串
我正在使用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');
但是,由于您将字符串data =
连接到console.log()
调用中的数据,因此将记录的是data.toString()
,它将返回对象的字符串表示forms,即[object Object]
。 因此,您将要在单独的console.log()
调用中记录data
。 像这样的东西:
$.post("getSale.php", function(data) { data = JSON.parse(data); console.log('data = '); // is showing the data with double quotes console.log(data); }, 'json');
您正在尝试使用您收到的数据到底是什么? 如果您只是想获取JSON消息的特定键,即“ {"name":"sam"}"
那么(假设您有一个JSON对象而不是JSON数组)无论双引号如何都能使用data.name
。