2013-03-15 52 views
3

有沒有一種方法能靠它生活在視圖的初始渲染CGridView 負荷數據,而是使其與初始頁面加載後,後續的AJAX請求加載的第一頁?的Yii:如何強制CGridview僅通過AJAX加載數據?

這主要是進行性能優化。有是相當緩慢的背後是一個CGridView數據模型,並且我希望能夠有一個活潑的方式在頁面加載,然後讓數據與AJAX請求的幾秒鐘後加載。

回答

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}"); 
}); 
+0

isAjaxRequest()不是控制器的方法。它是CHttpRequest的一個屬性。所以,雖然你可以檢查Ajax請求,例如,如果(Yii的應用::() - >請求 - > isAjaxRequest)...然後通過加入條件和更新功能這個建議的方案進行,這並未」實際上工作。電網根本不加載。一旦我弄清楚,我會回來發佈一個工作解決方案。 – 2013-09-07 17:09:20

0

布魯爾峽谷非常接近,並感謝他的建議的答案,它把我放在正確的軌道上。這工作:

// 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> 
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