本文介绍了无法获取以Json返回的Yii2对象数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Yii2框架和PHP的新手.当我尝试以json的形式从服务器检索模型数据时,得到的结果为空.但是,当我使用var_dump时,得到的是非空结果.

I am new to the Yii2 framework and PHP. When I try to retrieve a model data from the server as json, I am getting an empty result. But, when I use var_dump, I am getting a non-empty result.

控制器类代码:

public function actionIndex() {          
    $client = new Client();
    $client->name = "ajith";
    echo json_encode($client);
}

模型类代码:

class Client extends \yii\mongodb\ActiveRecord {
    public static function collectionName() {
        return ['gym', 'client'];
    }

    public function attributes() {
        return ['_id', 'name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'];
    }

    public function rules() {
        return [
            [['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
        ];
    }

    public function attributeLabels() {
        return [
            '_id'  => 'ID',
            'name' => 'Name',
            'age'  => 'Age',
            'sex'  => 'Sex',
            'phoneno'  => 'Phoneno',
            'email'    => 'Email',
            'address'  => 'Address',
            'location' => 'Location'
        ];
    }
}

当我使用URL路径pathToServer/web/client时,得到的结果回显为{}.为什么会这样呢?我使用MongoDB作为数据库.

When I use the URL path pathToServer/web/client, I am getting result echoed as {}. Why is it so? I use MongoDB as the database.

推荐答案

导入响应类:

use yii\web\Response;

通过在return之前设置Yii::$app->response->format

public function actionIndex() {    
    Yii::$app->response->format = Response::FORMAT_JSON;        
    $data = ["success" => true, "message" => "Hello World"];
    return $data;
}

响应结果:

{
    "success": true,
    "message": "Hello World"
}

您可以在 yii2中阅读有关响应格式的信息. -cookbook

这篇关于无法获取以Json返回的Yii2对象数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:55