Yii 1开发日记 -- Ajax实现点击加载下一页

时间:2021-10-13 10:31:42

  功能实现:先输出一页的内容,然后点击加载下一页,如图

  Yii 1开发日记 -- Ajax实现点击加载下一页

  1.控制器中

     /**
* 消费记录:列出用户购买章节的记录
*/
public function actionMyPayHis()
{
//点击加载更多
if( Yii::app()->request->isAjaxRequest ) {
//分页
$pg = isset( $_GET[ "pg" ] ) ? $_GET[ "pg" ] : 1;
$page = max( 0 , $pg );
$offset = $page * 3;
$accountLogs = B2cAccountLog::model()->findAll( array( 'condition' => 'user_id = :user_id and change_type = :change_type' ,
'params' => array( ':user_id' => Yii::app()->user->getId() , ':change_type' => B2cAccountLog::NOVEL_USER_READ_PAY ) ,
'order' => 'change_time desc' ,
'offset' => $offset ,
'limit' => 3
) ); $tpl = '<tr>
<td class="text-center">%s</td>
<td class="text-center">%s 桃花币</td>
<td class="text-center">
%s
</td>
</tr>'; $data = array();
$html = '';
foreach ( $accountLogs as $accountLog ) {
$html .= sprintf( $tpl ,
$accountLog->change_desc ,
DycUtil::toFloat( $accountLog->user_money ) ,
DycUtil::getTim2DateTime( $accountLog->change_time , 1 )
);
} $data = array( 'type' => 'ok' , 'info' => $html ); echo CJSON::encode( $data );
return; } else { $accountLogs = B2cAccountLog::model()->findAll( array( 'condition' => 'user_id = :user_id and change_type = :change_type' ,
'params' => array( ':user_id' => Yii::app()->user->getId() , ':change_type' => B2cAccountLog::NOVEL_USER_READ_PAY ) ,
'order' => 'change_time desc' ,
'offset' => 0 ,
'limit' => 3
) ); $this->render( 'myPayHis' , array( 'accountLogs' => $accountLogs ) );
} }

  先输出第一页的内容,再ajax请求输出下一页。

  2.视图中

     <div id="czjl" style="padding: 0 20px;">
<table class="am-table">
<thead>
<tr>
<th class="text-center">图书章节</th>
<th class="text-center">消费</th>
<th class="text-center">时间</th>
</tr>
</thead>
<tbody id="data_tr">
<?php
foreach ($accountLogs as $accountLog) {
?>
<tr>
<td class="text-center"><?= $accountLog->change_desc ?></td> <td class="text-center"><?= DycUtil::toFloat( $accountLog->user_money ) ?>桃花币</td>
<td class="text-center">
<?= DycUtil::getTim2DateTime( $accountLog->change_time , 1 ) ?>
</td> </tr>
<?php
}
?>
</tbody>
</table>
</div>
<div style="display: flex;justify-content: space-around;">
<div>
<span class="btn btn-default" id="loadmore">加载更多</span>
</div>
</div>

  加载更多,加一个 "id",绑定事件;"tbody"加一个"id",用来添加下一页的内容。

  3. JS实现

 <script type="application/javascript">

     var url = '<?= $this->createUrl( '/Novel/Hyzx/MyPayHis' ) ?>';
var i = 1;
var load = $('#loadmore');
//根据页数读取数据
function getData(page) {
i++; //页码自动增加,保证下次调用时为新的一页。
$.ajax({
type: "get",
url: url,
data: {pg: page},
dataType: "json",
success: function (data) {
if (data.info.length > 0) {
$('#data_tr').append(data.info);
} else {
load.html('没有更多的数据了....');
load.unbind()
}
},
error:function( request, textStatus ){
alert('请求失败,请稍候再试!' + textStatus);
}
});
} //点击加载下一页
$(function () {
load.on('click', function(){
getData(i);
});
});
</script>

  核心代码,定义一个函数,然后点击时,调用。点击一次,"i"加1,保证最新一页。

  小记:小而美,工匠精神。