如何在 yii 中获得 json 格式(应用程序/json)的响应? [英] How to get response as json format(application/json) in yii?
本文介绍了如何在 yii 中获得 json 格式(应用程序/json)的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 yii 中以 json 格式(application/json)获取响应?
How to get response as json format(application/json) in yii?
推荐答案
对于 Yii 1:
在你的(基础)控制器中创建这个函数:
For Yii 1:
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);
对于 Yii 2:
Yii 2 内置了这个功能,在您的控制器操作末尾使用以下代码:
For Yii 2:
Yii 2 has this functionality built-in, use the following code at the end of your controller action:
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
这篇关于如何在 yii 中获得 json 格式(应用程序/json)的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文