在列表视图中显示JSON数据yii2
问题描述:
我有一个问题可以在yii2的列表视图中显示JSON数据吗?在列表视图中显示JSON数据yii2
另一个问题是,这里是我的view
代码
<div class="panel-group" id="accordion">
<?= \yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'listview',
'layout' => "{pager}\n{items}\n{pager}",
]); ?>
</div>
这里是我的listview.php
文件代码
<div data-toggle="collapse" href="#collapse'<?= $model->id ?>'" id="title" class="panel-heading ads-heading">
<h4 class="panel-title"><?= $model->title ?></h4>
<div class="pull-right">
<button type="button" id="'<?= $model->id ?>'" onclick="AdsPost(this)"
class="checkin-btn btn btn-xs btn-danger"> View Ads
</button>
</div>
</div>
这里是我的controller
代码
public function actionEvent()
{
$connection=Yii::$app->db;
$command = $connection->createCommand("SELECT * from Advertisement where maincategory=2 AND subcategory=5");
$dataReader=$command->queryAll(); // execute a query SQL
$dataProvider = new ActiveDataProvider([
'query' => $data,
]);
return $this->render('event' ,['dataProvider' => $dataProvider]);
}
我也尝试过的东西像这样,但它的工作还不如
$query = new Query();
$query ->select(['*'])
->from('Advertisement')
->where('maincategory=1')
$command = $query->createCommand();
$data = $command->queryAll();
$dataProvider = new ActiveDataProvider([
'query' => $data,
]);
return $this->render('index' ,['dataProvider' => $dataProvider]);
那么我在这里做错了什么? 我问的问题来处理JSON数据以及因为如果我可以直接发送JSON数据到Listview
比它使我的生活很容易
如果它太复杂,我也可以用这个来管理。
答
你可以试试两个这样
在这种firts的错误是的$数据的分配,而不是$ DataReader的
public function actionEvent()
{
$connection=Yii::$app->db;
$command = $connection->createCommand("SELECT * from Advertisement where maincategory=2 AND subcategory=5");
$dataReader=$command->queryAll(); // execute a query SQL
$dataProvider = new ActiveDataProvider([
'query' => $dataReader,
]);
return $this->render('event' ,['dataProvider' => $dataProvider]);
}
或
$query = new Query();
$query->from('Advertisement')
->where('maincategory = 2 and subcategory = 5');
$command = $query->createCommand();
$data = $command->queryAll();
$dataProvider = new ActiveDataProvider([
'query' => $data,
]);
return $this->render('index' ,['dataProvider' => $dataProvider]);