当试图输出从服务器返回的json数据时,值显示未定义


Value showing undefined when trying to output data returned as json from server

我是第一次使用Yii2框架和PHP。我使用mongodb作为后台数据库。我从集合中获取文档,并从控制器以Json形式返回数据。返回的数据如下:

{
    "55b08c383e1a36233fdbdc06": { 
        "_id": { "$id": "55b08c383e1a36233fdbdc06" }, 
        "address": [ "abcdgt", "zxcv" ], 
        "age": "23", 
        "email": [ "qwert@gmail.com","abcd@mail.com" ], 
        "location": "kollam", 
        "name": "ajiths",
        "phoneno": [ "9522585456", "7875642256" ] ,
        "sex": "male" 
     }
}

但是当我试图在Javascript代码中警告result.name时,我得到了"未定义"。前端代码如下:

function loadClient(id){
         url = "<?=  Yii::getAlias('@serverpathweb')?>/client/showclient?id="+id;
           $.ajax({
          url: url ,
          method: "GET",
           success: function(result){
             alert(result.name);
                 }
             });
    }

控制器端的代码如下:

public function actionShowclient($id) {
       $clientdetail = Yii::$app->mongodb->getCollection('client');
       $result = $clientdetail->find(["_id" =>$id]);
       Yii::$app->response->format = 'yii'web'Response::FORMAT_JSON;
       return $result;
    }

谁能告诉我如何获得值result.name

你得到的JSON结果id为key,所以访问我们的JSON数据像这样首先使用Object.keys获取JSON的键接下来使用key打印您需要的值

var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name

注意,如果你得到多个用户的详细信息,请让我知道

你的"result"对象可能是一个String,因为你没有告诉jQuery。尝试将选项dataType:json添加到您的请求中,如:

$.ajax({ url: url, method: 'GET', dataType: 'json', etc...

编辑:看起来你的代码中也有一个简单的错误。您需要访问嵌套在结果对象中的属性:

result[id].name