YII中ajax分页有多种实现方法,比较传统的就是在view中写JS来实现,大概的就是这样:
在view中js大概逻辑是这样:
1 |
$('#listview .yiiPager a').live('click',function(){ |
3 |
url:$(this).attr('href'), |
4 |
success:function(html){ |
5 |
$('#listview').html(html); |
然后在controller中判断ajax请求,再使用renderPartial方法渲染局部List视图,然后局部视图会被view中的ajax
方法填充到局部刷新的div中。controller的大概逻辑是:
1 |
if (Yii::app()->request->isAjaxRequest) { |
2 |
$this->renderPartial('_comments',array( |
4 |
'comments' => $comments, |
后来发现YII中的CListview更方便,封装了分页,foreach显示list,还支持数据排序。具体的可以在YII的API手册
中发掘。使用CListview是默认ajax分页的,使用方法如下:
controller中:
01 |
$criteria = new CDbCriteria(); |
02 |
$criteria->order = '`create_time` DESC'; |
04 |
$dataProvider = new CActiveDataProvider('Comments', array( |
06 |
'pageSize'=>Yii::app()->params['commentsPerPage'], |
08 |
'criteria'=>$criteria, |
10 |
$this->render('comments',array( |
12 |
'dataProvider' => $dataProvider, |
然后在view中:
01 |
<?php $this->widget('zii.widgets.CListView', array( |
02 |
'dataProvider'=>$dataProvider, |
03 |
'itemView'=>'_comments', |
06 |
'nextPageLabel' => '下一页 »', |
07 |
'prevPageLabel' => '« 上一页' |
这样就实现了Ajax分页,很方便。