How to get response as json format(application/json) in yii?

后端 未结 8 1139
小鲜肉
小鲜肉 2021-01-30 05:08

How to get response as json format(application/json) in yii?

8条回答
  •  梦谈多话
    2021-01-30 05:46

    For Yii 1:

    Create this function in your (base) Controller:

    /**
     * Return data to browser as JSON and end application.
     * @param array $data
     */
    protected function renderJSON($data)
    {
        header('Content-type: application/json');
        echo CJSON::encode($data);
    
        foreach (Yii::app()->log->routes as $route) {
            if($route instanceof CWebLogRoute) {
                $route->enabled = false; // disable any weblogroutes
            }
        }
        Yii::app()->end();
    }
    

    Then simply call at the end of your action:

    $this->renderJSON($yourData);
    

    For Yii 2:

    Yii 2 has this functionality built-in, use the following code at the end of your controller action:

    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $data;
    

提交回复
热议问题