2017-07-13 143 views
1

我有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,在哪裏以及如何正確地做到這一點?

+0

但是,什麼是exacly問題? – Yupik

回答

0

在Yii2你需要從你的行動與JSON返回結果,例如:

public function actionIndex() 
{ 
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 

    $query = Country::find(); 

    $countries = $query->orderBy('name')->all(); 

    return $countries; 
}