【问题标题】:Not able to get Yii2 object data returned as Json无法获取以 Json 形式返回的 Yii2 对象数据
【发布时间】:2015-07-27 09:31:14
【问题描述】:

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

控制器类代码:

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 作为数据库。

【问题讨论】:

  • 尝试在你的控制器动作中使用返回,这就是 Yii2 响应对象期望从控制器动作返回的结果

标签: php json mongodb yii2


【解决方案1】:

导入响应类:

use yii\web\Response;
use Yii;

return之前设置Yii::$app->response->format,告诉Yii你想要什么格式的结果

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 中阅读有关响应格式的信息

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2014-11-01
    • 2020-09-27
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多