如何在yii中以json格式(application / json)获得响应?
答案 0 :(得分:84)
在(基础)控制器中创建此功能:
/**
* 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 has this functionality built-in,在控制器操作结束时使用以下代码:
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
答案 1 :(得分:18)
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end();
答案 2 :(得分:14)
对于控制器内的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;
}
答案 3 :(得分:9)
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
答案 4 :(得分:5)
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');
}
}
答案 5 :(得分:0)
使用
的一种更简单的方法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);
}
}
欢呼:)
答案 6 :(得分:0)
在要呈现JSON数据的控制器操作中,例如: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
}
查看更多Yii API
答案 7 :(得分:-1)
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;
}
因此,即使在之后,应用程序流仍继续执行。