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

gajydyqb  于 2022-11-09  发布在  其他
关注(0)|答案(9)|浏览(182)

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

mrphzbgm

mrphzbgm1#

对于Yii 1:

在(基本)控制器中创建此函数:

/**
 * 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();
}

然后在你的动作结束时简单地调用:

$this->renderJSON($yourData);

对于Yii 2:

Yii 2内置了此功能,请在控制器操作的末尾使用以下代码:

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

uqxowvwt2#

对于控制器内的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;
}
btqmn9zl

btqmn9zl3#

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

nom7f22z4#

$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
4dc9hkyq

4dc9hkyq5#

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');
    }

}
qv7cva1a

qv7cva1a6#

对于Yii2,使用这个简单易记选项

Yii::$app->response->format = "json";
return $data
hwazgwia

hwazgwia7#

一个更简单的方法,

echo CJSON::encode($result);

示例代码:

public function actionSearch(){
    if (Yii::app()->request->isAjaxRequest && isset($_POST['term'])) {
            $models = Model::model()->searchNames($_POST['term']);
            $result = array();
            foreach($models as $m){
                $result[] = array(
                        'name' => $m->name,
                        'id' => $m->id,
                );

            }
            echo CJSON::encode($result);
        }
}

欢呼声:)

5tmbdcev

5tmbdcev8#

在您想要呈现JSON数据的控制器动作中,例如:动作Json()

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

查看更多Yii API

ny6fqffe

ny6fqffe9#

Yii::app()->end()

我认为这个解决方案并不是结束应用程序流的最好方法,因为它使用了PHP的exit()函数,这意味着立即退出执行流。是的,Yii有onEndRequest处理程序,PHP有register_shutdown_function处理程序,但它仍然太宿命论了。
对我来说更好的方法是

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;
}

因此,应用程序流即使在之后也会继续执行。

相关问题