Php 正确访问JSON对象

Php 正确访问JSON对象,php,jquery,arrays,json,element,Php,Jquery,Arrays,Json,Element,我试图访问从服务器返回的JSON对象中的元素。JSON的结构如下所示: ajaxResponse: { "user":{ "0":"Matt", "name":"Matt", "1":"/images\/peopleImages\/test.jpg", "image":"/images\/peopleImages

我试图访问从服务器返回的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" );              
                }   
            );

好的,我忘了调用
parseJSON

      var data = $.parseJSON(ajaxResponse);

      console.log("response2: " + data.user.name);

这似乎是正确的,并允许我正确获取名称。

从服务器返回内容时:

echo json_encode($ajaxResponse);
发送邮件时:

dataType: "json"
基于此,您可能会得到:

ajaxResponse.user

试着安慰它。

对于Json对象的直接使用,您需要通知dataType=“Json”,然后您可以使用jQuery中的$.ajax发送post值和正确的数据类型

请参阅此处的文档:


缺少
1”
…然后
ajaxResponse:
???您是否获得了
ajaxResponse的有效对象。用户
?首先在此处检查您的JSON:您确定ajaxResponse的定义与您期望的一样吗?这只是一个打字错误-我得到的JSON很好-我刚刚在这里重新构造了它,以便更容易阅读。是,AJAX响应正确-我无法正确访问它。
$.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"
});