引言
眾所周知,Thinkphp有自帶的分頁功能,但主要是通過對(duì)網(wǎng)頁 的刷新實(shí)現(xiàn)。因?yàn)槊看嗡⑿戮W(wǎng)頁都需要加載靜態(tài)資源,程序開銷比較大。同時(shí),由于每次刷新網(wǎng)頁時(shí)頁面跳轉(zhuǎn)給用戶的體驗(yàn)感較差。所以,這里通過Ajax,實(shí)現(xiàn)網(wǎng)頁的局部刷新,不僅程序開銷減小,而且增強(qiáng)了用戶的體驗(yàn)。
方法
1. 首先在項(xiàng)目的Common中添加修改的分頁類
<?php
// +----------------------------------------------------------------------
// Illustrate: 修改的AjaxPage 分頁類
// +----------------------------------------------------------------------
//
namespace Admin\Common;
class AjaxPage {
// 分頁欄每頁顯示的頁數(shù)
public $rollPage = 5;
// 頁數(shù)跳轉(zhuǎn)時(shí)要帶的參數(shù)
public $parameter ;
// 默認(rèn)列表每頁顯示行數(shù)
public $listRows = 10;
// 起始行數(shù)
public $firstRow ;
// 分頁總頁面數(shù)
protected $totalPages ;
// 總行數(shù)
protected $totalRows ;
// 當(dāng)前頁數(shù)
protected $nowPage ;
// 分頁的欄的總頁數(shù)
protected $coolPages ;
// 分頁顯示定制
protected $config = array('header'=>'條記錄','prev'=>'上一頁','next'=>'下一頁','first'=>'第一頁','last'=>'最后一頁','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 頁 %upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
// 默認(rèn)分頁變量名
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); //總頁數(shù)
$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); //總頁數(shù)
$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中找到要刷新的局部頁面顯示代碼,然后在對(duì)應(yīng)的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>
<!--如果對(duì)應(yīng)的AjaxPage頁面有相應(yīng)的Action操作,需要添加相應(yīng)的jquery或js方法,否則局部頁面刷新時(shí)不響應(yīng)-->
<script type="text/javascript">
function delOneRecord(e)
{
bootbox.confirm({
title: "系統(tǒng)提示",
message: "是否要?jiǎng)h除所選記錄?",
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");
//產(chǎn)生分頁信息
$page=$p->show();
$this->assign('list',$list);
$this->assign('page',$page);
$this->display();
//判斷,如果是Ajax,返回局部頁面數(shù)據(jù)到前臺(tái)
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. 注意事項(xiàng)
- Controller方法中的
$p=new \Admin\Common\AjaxPage($count,10,"server");第三個(gè)func參數(shù)要與js中func 名稱一致 - 使用局部刷新時(shí),要將Page和要替換的模板放在一起。
- 渲染模板要與替換模板一致,而且替換模板中的涉及到的js方法要在渲染模板中也要列出來。
6. 參考