How to get response as json format(application/jso

2019-03-07 23:22发布

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

标签: php yii
8条回答
Luminary・发光体
2楼-- · 2019-03-07 23:39

In the controller action that you want to render JSON data, e.g: actionJson()

public function actionJson(){
    $this->layout=false;
    header('Content-type: application/json');
    echo CJSON::encode($data);
    Yii::app()->end(); // equal to die() or exit() function
}

See more Yii API

查看更多
劫难
3楼-- · 2019-03-07 23:43
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end(); 
查看更多
放荡不羁爱自由
4楼-- · 2019-03-07 23:45
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');
    }

}
查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-07 23:47

For Yii2 inside a controller:

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;
}
查看更多
劫难
6楼-- · 2019-03-07 23:49
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end(); 
查看更多
干净又极端
7楼-- · 2019-03-07 23:50
Yii::app()->end()

I think this solution is not the best way to end application flow, because it uses PHP's exit() function, witch means immediate exit from execution flow. Yes, there is Yii's onEndRequest handler, and PHP's register_shutdown_function but it still remains too fatalistic.

For me the better way is this

public function run($actionID) 
{
    try
    {
        return parent::run($actionID);
    }
    catch(FinishOutputException $e)
    {
        return;
    }
}

public function actionHello()
{
    $this->layout=false;
    header('Content-type: application/json');
    echo CJavaScript::jsonEncode($arr);
    throw new FinishOutputException;
}

So, the application flow continues to execute even after.

查看更多
登录 后发表回答