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条回答
何必那么认真
2楼-- · 2019-03-07 23:54

one more simple way by using

echo CJSON::encode($result);

example code:

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

cheers :)

查看更多
乱世女痞
3楼-- · 2019-03-07 23:55

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);
查看更多
登录 后发表回答