Yiiの中にJSON形式(アプリケーション/ JSON)として応答を取得するには?
質問
のYiiでJSON形式(アプリケーション/ JSON)としての応答を取得するには?
解決
の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;
他のヒント
$this->layout=false;
header('Content-type: application/json');
echo CJavaScript::jsonEncode($arr);
Yii::app()->end();
コントローラ内部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 json_encode($arr);
Yii::app()->end();
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');
}
}
を使用して、
1つの、より簡単な方法
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);
}
}
歓声:)
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;
}
だから、アプリケーションフローにも後に実行を継続します。
所属していません StackOverflow