如何在Yii框架中以JSON格式(application/json)获取响应?
在您的(基础)控制器中创建此函数:
/**
* 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::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
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;
}
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end();
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
$this->layout=false
,因为Yii::app()->end()
会终止应用程序而不输出布局。 - Ethanclass 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');
}
}
。
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);
}
}
cheers :)
对于Yii2,使用这个简单易记的选项
Yii::$app->response->format = "json";
return $data
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;
}
ob_start(); Yii::app()->end(0, false); ob_end_clean(); exit(0);
- marcovtwout