我正在尝试访问从服务器返回的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']
但是工作的nothings我总是得到类型错误是未定义的。 任何帮助将不胜感激!
修改
这就是我获得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" );
}
);
答案 0 :(得分:0)
好的,我忘了拨打parseJSON
var data = $.parseJSON(ajaxResponse);
console.log("response2: " + data.user.name);
这似乎纠正了它并允许我正确地取回名称。
答案 1 :(得分:0)
从服务器返回内容时:
echo json_encode($ajaxResponse);
发送POST时:
dataType: "json"
基于此,你可能会得到它:
ajaxResponse.user
尝试安慰它。
答案 2 :(得分:0)
要直接使用Json对象,您需要通知dataType =“json”,然后您可以使用jQuery中的$ .ajax发送post值和更正数据类型。
请参阅此处的文档:http://api.jquery.com/jquery.post/
$.ajax({
type: "POST",
url: "script.php",
data: {
task: 'commentInsert',
userId: commentUserId,
postId: '2',
userComment: comment
}
success: function(ajaxResponse){
console.log("response: " + ajaxResponse);
console.log(ajaxResponse[0].user.name);
} ,
dataType: "json"
});