Yii:如何强制CGridview只通过AJAX加载数据?

时间:2013-03-15 23:08:53

标签: yii

有没有办法让CGridView 在其所在的视图的初始渲染上加载数据,而是在初始页面加载后使其加载第一页以及后续的AJAX请求?

这主要用于性能优化。有一个数据模型在CGridView背后相当缓慢,我希望能够以一种快速的方式加载页面,然后在几秒钟之后通过AJAX请求加载数据。

3 个答案:

答案 0 :(得分:4)

您可以按如下方式修改操作:

public function actionIndex() {
  $dataProvider = new CActiveDataProvider('User'); // The dataprovider your grid uses
  if (!$this->isAjaxRequest()) {
    $dataProvider->criteria->addCondition('1 = 0'); // You could also use 0, but I think this is more clear
  }

  [...]
}

然后在javascript部分的视图中:

$(function() { // If you are using jQuery this is executed when the page is loaded
  $.fn.yiiGridView.update("{id-of-your-grid-view}");
});

答案 1 :(得分:0)

Brewer Gorge非常接近,并且由于他建议的答案,它让我走上正轨。这有效:

// Controller, after creating $dataProvider, before calling $this->render...
if (!Yii::app()->request->isAjaxRequest) {
    $dataProvider->criteria->addCondition('1 = 0');
}

// View
<script type="text/javascript">
$(window).load(function() {
    $('#id-of-grid').yiiGridView('update');
});
</script>

答案 2 :(得分:0)

只需在控制器中编写代码,如下所示:

$model= new Data('search');
$model->unsetAttributes();

if(isset($_GET['Data']))
   $model->attributes = $_GET['Data'];

if (!Yii::app()->request->isAjaxRequest)
   $data->id=0; //or something that sure model return empty