gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:31:16 25 4
gpt4 key购买 nike

我正在使用 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]。因此,您需要在单独的 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');

关于jQuery $.post 和 json_encode 返回一个带有引号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263262/

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