如何以JSON格式显示信息?
问题描述:
我有Yii2基础,并希望从这一课https://github.com/yiisoft/yii2/blob/master/docs/guide/start-databases.md(无分页)显示页面如何以JSON格式显示信息?
Controller return:
return $this->render('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
查看文件:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?>
<li>
<?= Html::encode("{$country->name} ({$country->code})") ?>:
<?= $country->population ?>
</li>
<?php endforeach; ?>
</ul>
也许我应该改变主要布局以显示JSON,在哪里以及如何正确地做到这一点?
答
在Yii2你需要从你的行动与JSON返回结果,例如:
public function actionIndex()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$query = Country::find();
$countries = $query->orderBy('name')->all();
return $countries;
}
但是,什么是exacly问题? – Yupik