引言
众所周知,Thinkphp有自带的分页功能,但主要是通过对网页 的刷新实现。因为每次刷新网页都需要加载静态资源,程序开销比较大。同时,由于每次刷新网页时页面跳转给用户的体验感较差。所以,这里通过Ajax,实现网页的局部刷新,不仅程序开销减小,而且增强了用户的体验。
方法
1. 首先在项目的Common中添加修改的分页类
<?php
// +----------------------------------------------------------------------
// Illustrate: 修改的AjaxPage 分页类
// +----------------------------------------------------------------------
//
namespace Admin\Common;
class AjaxPage {
// 分页栏每页显示的页数
public $rollPage = 5;
// 页数跳转时要带的参数
public $parameter ;
// 默认列表每页显示行数
public $listRows = 10;
// 起始行数
public $firstRow ;
// 分页总页面数
protected $totalPages ;
// 总行数
protected $totalRows ;
// 当前页数
protected $nowPage ;
// 分页的栏的总页数
protected $coolPages ;
// 分页显示定制
protected $config = array('header'=>'条记录','prev'=>'上一页','next'=>'下一页','first'=>'第一页','last'=>'最后一页','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
// 默认分页变量名
protected $varPage;
public function __construct($totalRows,$listRows='',$ajax_func,$parameter='') {
$this->totalRows = $totalRows;
$this->ajax_func = $ajax_func;
$this->parameter = $parameter;
$this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ;
if(!empty($listRows)) {
$this->listRows = intval($listRows);
}
$this->totalPages = ceil($this->totalRows/$this->listRows); //总页数
$this->coolPages = ceil($this->totalPages/$this->rollPage);
$this->nowPage = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
$this->nowPage = $this->totalPages;
}
$this->firstRow = $this->listRows*($this->nowPage-1);
}
public function nowpage($totalRows,$listRows='',$ajax_func,$parameter='') {
$this->totalRows = $totalRows;
$this->ajax_func = $ajax_func;
$this->parameter = $parameter;
$this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ;
if(!empty($listRows)) {
$this->listRows = intval($listRows);
}
$this->totalPages = ceil($this->totalRows/$this->listRows); //总页数
$this->coolPages = ceil($this->totalPages/$this->rollPage);
$this->nowPage = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
$this->nowPage = $this->totalPages;
}
$this->firstRow = $this->listRows*($this->nowPage-1);
return $this->nowPage;
}
public function setConfig($name,$value) {
if(isset($this->config[$name])) {
$this->config[$name] = $value;
}
}
public function show() {
if(0 == $this->totalRows) return '';
$p = $this->varPage;
$nowCoolPage = ceil($this->nowPage/$this->rollPage);
$url = $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
$parse = parse_url($url);
if(isset($parse['query'])) {
parse_str($parse['query'],$params);
unset($params[$p]);
$url = $parse['path'].'?'.http_build_query($params);
}
//上下翻页字符串
$upRow = $this->nowPage-1;
$downRow = $this->nowPage+1;
if ($upRow>0){
$upPage="<a class='ajaxify' id='big' href='JavaScript:".$this->ajax_func."(".$upRow.")'>".$this->config['prev']."</a>";
}else{
$upPage="";
}
if ($downRow <= $this->totalPages){
$downPage="<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$downRow.")'>".$this->config['next']."</a>";
}else{
$downPage="";
}
// << < > >>
if($nowCoolPage == 1){
$theFirst = "";
$prePage = "";
}else{
$preRow = $this->nowPage-$this->rollPage;
$prePage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$preRow.")'>上".$this->rollPage."页</a>";
$theFirst = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(1)' >".$this->config['first']."</a>";
}
if($nowCoolPage == $this->coolPages){
$nextPage = "";
$theEnd="";
}else{
$nextRow = $this->nowPage+$this->rollPage;
$theEndRow = $this->totalPages;
$nextPage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$nextRow.")' >下".$this->rollPage."页</a>";
$theEnd = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$theEndRow.")' >".$this->config['last']."</a>";
}
// 1 2 3 4 5
$linkPage = "";
for($i=1;$i<=$this->rollPage;$i++){
$page=($nowCoolPage-1)*$this->rollPage+$i;
if($page!=$this->nowPage){
if($page<=$this->totalPages){
$linkPage .= " <a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$page.")'> ".$page." </a>";
}else{
break;
}
}else{
if($this->totalPages != 1){
$linkPage .= " <span class='current'>".$page."</span>";
}
}
}
$pageStr = str_replace(
array('%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'),
array($this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd),$this->config['theme']);
return $pageStr;
}
}
?>
2. 在html中找到要刷新的局部页面显示代码,然后在对应的Controller下建立渲染模板
<div id="temp">
<form id="form" name="form" method="post" action="" onSubmit="click();">
<div class="table-responsive" >
<table class="table table-striped table-bordered table-hover">
<thead>
<tr style="font-size:14.1px;">
<th class="center"><input class="check-all" type="checkbox" value=""></th>
</tr>
</thead>
<tbody>
<volist name="list" id="val">
<tr id="record" style="font-size:14.05px;">
<td align="center">
<input class="uids" type="checkbox" name="uids[]" value="{$val['uid']}">
</td>
<a <if condition="$val['l_check'] eq 1">
href ="javascript:volid(0);"
<else/>
href="{:U('edit',array('uid'=>$val['uid']))}"
</if>>修改</a>
<a data-name="{$val['uid']}"
<if condition="$val['l_check'] eq 1">
href ="javascript:volid(0);"
<else/>
href="javascript:void(0);" onclick="delOneRecord(this)"
</if>
title="删除">删除</a>
</td>
</tr>
</volist>
</tbody>
</table>
</div>
</form>
<div class="page">
{$page}
</div>
</div>
<!--如果对应的AjaxPage页面有相应的Action操作,需要添加相应的jquery或js方法,否则局部页面刷新时不响应-->
<script type="text/javascript">
function delOneRecord(e)
{
bootbox.confirm({
title: "系统提示",
message: "是否要删除所选记录?",
callback: function (result) {
var uids=e.getAttribute("data-name");
uids = encodeURIComponent(uids);
$.get("{:U('del')}", {"uids":uids}, function(data)
{
$(e).parents("tr").delay(500).fadeOut(700);
});
},
buttons: {
"cancel": {"label": "取消"},
"confirm": {
"label": "确定",
"className": "btn-danger"
}
}
});
}
$(".check-all").click(function () {
$(".uids").prop("checked", this.checked);
});
$(".uids").click(function () {
var option = $(".ids");
option.each(function (i) {
if (!this.checked) {
$(".check-all").prop("checked", false);
return false;
} else {
$(".check-all").prop("checked", true);
}
});
});
</script>
3. 控制器方法
public function getPageContent()
{
$uid =intval(session('uid'));
$inst = trim(session('inst'));
$user = M();
$count = count($user -> query("SELECT *,c.sex AS csex,m.sex AS msex from contractor as co join member as m on co.uid=m.uid join chenglan_record as c on c.chl_name=co.cname where m.uid = $uid and c.chenglan_inst = $inst"));
$p=new \Admin\Common\AjaxPage($count,10,"server");
$limit_value = $p->firstRow . "," . $p->listRows;
$list = $user -> query("SELECT *,c.sex AS csex,m.sex AS msex from contractor as co join member as m on co.uid=m.uid join chenglan_record as c on c.chl_name=co.cname where m.uid = $uid and c.chenglan_inst = $inst limit $limit_value");
//产生分页信息
$page=$p->show();
$this->assign('list',$list);
$this->assign('page',$page);
$this->display();
//判断,如果是Ajax,返回局部页面数据到前台
if(IS_AJAX)
{
$res["content"]=$this->fetch('ajaxPage');
$this->ajaxReturn($res);
}
}
4. js代码
function server(id)
{
var id = id;
$.get("{:U('getPageContent')}", {"p":id}, function(data)
{
$("#temp").replaceWith("<div id='temp'>"+data.content+" </div>");
});
}
5. 注意事项
- Controller方法中的
$p=new \Admin\Common\AjaxPage($count,10,"server");
第三个func参数要与js中func 名称一致 - 使用局部刷新时,要将Page和要替换的模板放在一起。
- 渲染模板要与替换模板一致,而且替换模板中的涉及到的js方法要在渲染模板中也要列出来。
6. 参考
网友评论