【发布时间】:2014-02-05 12:29:31
【问题描述】:
我正在尝试访问从服务器返回的 JSON 对象中的元素。 JSON的结构如下:
ajaxResponse:
{
"user":{
"0":"Matt",
"name":"Matt",
"1":"/images\/peopleImages\/test.jpg",
"image":"/images\/peopleImages\/test.jpg"
},
"comment":{
"userCommentID":21,
"userComment":"vc ",
"userID":1
},
"error":false
}
我已经尝试了几乎所有我能想到的:
ajaxResponse[0].user.name
ajaxResponse.user.name
ajaxResponse.user['name']
但是什么都没有,我总是得到类型错误是未定义的。 任何帮助将不胜感激!
编辑
这就是我获取 JSON 的方式
$.post( "script.php" ,
{
task: 'commentInsert',
userId: commentUserId,
postId: '2',
userComment: comment
}
).success(
function(ajaxResponse){
console.log("response: " + ajaxResponse);
console.log(ajaxResponse[0].user.name);
/*
ajaxResponse[0].user.name
ajaxResponse[0].user.image
ajaxResponse[0].comment.userCommentID
ajaxResponse[0].comment.userComment
ajaxResponse[0].comment.userId
insertComment($.parseJSON(ajaxResponse));
*/
}
).error(
function(){
console.log("error" );
}
);
【问题讨论】:
-
在
1"缺少"....然后ajaxResponse:??? -
您是否获得了
ajaxResponse.user的有效对象? -
首先在此处检查您的 JSON:jsonlint.com
-
您确定 ajaxResponse 的定义符合您的预期吗?
-
这只是一个错字——在我回来的 json 中它很好——我刚刚在此处对其进行了重组以便于阅读。是的 ajaxResponse 是正确的 - 我无法正确访问它。
标签: php jquery arrays json element