我有一个php返回一些json,以响应通过ajax函数发出的POST请求
在我的php函数中,我将数据格式化如下:
//json return
$return["answerswers"] = 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
进行解析
成功:函数(数据){var json=$.parseJSON(数据);alert(json.answers[0]["aa"]);}
像这样使用parseJson
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
如果删除PHP端的双重编码会怎样?您得到了一个带有JSON字符串的对象,而不是第一个属性为对象本身的对象,或者您可以像上面建议的那样在客户端显式地解码"answerswers"属性。