如何在yii中以json格式(application/json)获得响应?

tq0*_*qeu 51 php yii

如何在yii中以json格式(application/json)获得响应?

mar*_*out 87

在(基础)控制器中创建此功能:

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)

然后只需在行动结束时致电:

$this->renderJSON($yourData);
Run Code Online (Sandbox Code Playgroud)


Nei*_*gan 18

$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end(); 
Run Code Online (Sandbox Code Playgroud)


Ser*_*nko 16

对于控制器内的Yii2:

public function actionSomeAjax() {
    $returnData = ['someData' => 'I am data', 'someAnotherData' => 'I am another data'];

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

    return $response;
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.跟随Yii的api +1. (2认同)

tq0*_*qeu 9

$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end(); 
Run Code Online (Sandbox Code Playgroud)

  • 一些tewaks:使用CJSON :: encode()作为模型; 不需要`$ this-> layout = false`,因为`Yii :: app() - > end()`将终止应用程序而不输出布局. (4认同)

And*_*nko 5

class JsonController extends CController {

    protected $jsonData;

    protected function beforeAction($action) {
        ob_clean(); // clear output buffer to avoid rendering anything else
        header('Content-type: application/json'); // set content type header as json
        return parent::beforeAction($action);
    }

    protected function afterAction($action) {
        parent::afterAction($action);
        exit(json_encode($this->jsonData)); // exit with rendering json data
    }

}

class ApiController extends JsonController {

    public function actionIndex() {
        $this->jsonData = array('test');
    }

}
Run Code Online (Sandbox Code Playgroud)