【发布时间】:2013-11-22 07:06:21
【问题描述】:
我有一个 php 返回一些 json 以响应通过 ajax 函数发出的 POST 请求。
在我的 php 函数中,我像这样格式化数据:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
这将返回以下字符串:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
这就是我试图抓住它以使用数据的地方:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
我一直在尝试仅提醒数据,以便在设置所需的变量之前对其进行可视化,但在正确格式化它以使其可用时遇到了一些问题。
如果我提醒data.answers[0],那么它只会显示字符串中的第一个字符,即括号 [,如果我随后更改数字,它将遍历返回字符串中的每个字符。
我尝试过其他变体,例如:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
我觉得我很接近,但错过了一些东西。任何指导表示赞赏。
编辑:
感谢所有建议。我删除了第二个 json_encode 并能够使用 data.answers[0].aa 进行解析
【问题讨论】:
-
@palaѕн 刚刚做了,它返回未定义。还尝试了返回
Cannot read property '0' of undefined欢呼的 data.answers.aa[0]。 -
console.log(data)得到什么?请在此处发布... -
你可以使用 alert(JSON.stringify(data));
-
只要把这一行放到成功函数console.log(data)中;并检查萤火虫它会帮助你更多。
-
@SohilDesai 似乎只记录了我已经知道存在并格式化的字符串:
Object {answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue…"ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"}
标签: javascript php jquery ajax json