如何在 yii 中以 json 格式(应用程序/json)获得响应?
问问题
62348 次
9 回答
93
对于 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;
于 2012-10-23T13:21:00.747 回答
19
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end();
于 2010-12-18T00:24:43.530 回答
19
对于控制器内部的 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;
}
于 2015-09-02T06:29:57.090 回答
10
$this->layout=false;
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
于 2010-05-17T07:44:02.920 回答
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');
}
}
于 2013-06-29T21:03:10.190 回答
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);
}
}
干杯:)
于 2013-01-23T17:19:32.167 回答
0
对于 Yii2 使用这个简单易记的选项
Yii::$app->response->format = "json";
return $data
于 2021-08-16T13:40:21.213 回答
-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;
}
因此,即使在此之后,应用程序流程也会继续执行。
于 2012-03-29T10:58:42.063 回答