【发布时间】:2019-08-09 06:33:25
【问题描述】:
我有来自 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 调用,以将其传送到 Web 服务器上。:
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": "{...}" }
结果值是一个字符串,因为这些双引号!
这快把我逼疯了。我是否错过了防止这种情况发生的步骤?
【问题讨论】:
-
如果你的 MYSQL 已经返回了一个 json 字符串,为什么还要重新编码呢?
-
如果我不在 php 中做 json_encode(),我的 JS 说它会得到一个数组
-
你能用
JSON.parse(data)代替stringify吗? -
您需要展示如何获取行并对其进行编码。这就是问题所在。
-
@Rollor 你能在
return json_encode($query_result);之前做一个die(gettype($query_result));并发布结果吗?如果它是一个数组,请执行die(gettype($query_result['results']));