我有来自 MySql 的数据,从这里回答:
How to SQL query parent-child for specific JSON format? .基本上我使用 JSON_OBJECT()
查询它产生结果:
results
<-- The column name
{"projects": "project_name": "project 1", [2nd layer stuff]} <-- the row
太棒了。 MySql 为我做了 json 的事情。我对 PHP
进行了 ajax 调用函数将它放到网络服务器上。:
myPhpFunction () {
//some usual PDO code
echo json_encode($query_result);
}
在 JS 上,我进行 jQuery ajax 调用:
var ajaxRequest =
$.ajax({
type: 'post',
url: '../includes/ajax.php',
data: 'action' : 'myPhpFunction',
dataType: 'json'
});
ajaxRequest.done(function(data) {
//$.each(data[0].results.projects, function(key, val){
//I want to access each stuff in the object here
//}
$('#ph-projects').append(JSON.stringify(data)); //testing it out
}
我现在遇到的问题是,我的对象 data
像这样的输出:
{ "results": "{...}" }
由于那些双引号,结果值是一个字符串!
这让我发疯。我是否缺少防止这种情况发生的步骤?
最佳答案
json_encode()
工作正常,因为它按照您的问题建议将结果作为 JSON 对象提供({ "results": "{...}"}/
)。并且 PDO 中的 JSON_OBJECT()
返回字符串很好,正如名称 JSON 所暗示的那样,它的 JavaScript Object Notation 是一种人类可读的格式。
你可以在服务器端做:
json_encode(['results'=> json_decode($query_result['results'])]);
或在客户端,
function(data){
data.results = JSON.parse(data.results);
// Your json data here
}
关于php - 由于添加了双引号,json 对象变成了字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55229019/