TP2.0或3.1 或者 3.2 下使用ajax+php做无刷新分页(转+自创)

1.前言

    作为一名php程序员,我们开发网站主要就是为了客户从客户端进行体验,在这里,thinkphp框架自带的分页类是每次翻页都要刷新一下整个页面,这种翻页的用户体验显然是不太理想的,我们希望每次翻页只刷新我们想要的数据集部分的数据,这样可以给客户带来很好的体验效果。那么在TP下如何进行ajax无刷新分页呢?

  1.1建立ajax分页

    在TP框架的ThinkPHP\Library\Think文件夹下,有框架自己的page.class.php,我们新建一个Ajaxpage.class.php,下面这个类是我实际用到项目中的

        当然,你也可以不在这里建立,在需要的控制器方法里面可以 require_once "require_once APP_ROOT_PATH.'Ajaxpage.class.php';     //php加载ajax分页类"

<?php
//【如果使用了TP3.2,请在这里加上namespace Think;】
class Ajaxpage {
// 分页栏每页显示的页数
public $rollPage = 5;
// 页数跳转时要带的参数
public $parameter ;
// 默认列表每页显示行数
public $listRows = 20;
// 起始行数
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 = '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 = '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、ajax调用地址==》》 ajaxModule.class.php下的article_show_comment方法,返回结果:就是我们要替换的html数据和标签(注意:这里我写的是php的ajax方法,不是一个简单的method,通俗点就是jQuery的ajax里面的url)

public function article_show_comment(){
//统计要查询数据的数量
$page_size = 5; //评论固定5条
$page = intval($_REQUEST['p']);
$id = intval($_REQUEST['id']);
if(empty($page))$page = 1;
$limit = (($page-1)*$page_size).",".$page_size ; $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."article_comment where article_id = ".$id." and log_id = 0 and status=1 order by create_time desc limit ".$limit);
$count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."article_comment where article_id = ".$id." and log_id = 0 and status=1"); //TP3.2使用下面
//$where['status'] = array('gt',-1);
//$_REQURST['cond'] && $where['cond'] = $_REQURST['cond']; //多条件查询判断
// $list = M('Action')->where($where)->order('id desc')->limit($limit)->select();
// $count[0]['count'] = M('Action')->where($where)->count("*");
//end TP3.2
//实例化分页类,传入三个参数,分别是总记录数、每页显示条数、要调用的jQuery ajax方法名
require_once APP_ROOT_PATH.'app/Lib/Ajaxpage.class.php'; //php加载ajax分页类
$p = new Ajaxpage($count[0]['count'],$page_size,'index'); //'index'是jQuery里面ajax方法名
//产生分页信息
$page=$p->show();
//要查询的数据,limit表示每页查询的数量,这里为10条
//$data = $info->where($where)->limit($p->firstRow.','.$p->listRows)->select();
//assign方法往模板赋值
$GLOBALS['tmpl']->assign('list',$list); //模板变量赋值
$GLOBALS['tmpl']->assign('page',$page);
//ajax返回信息,就是要替换的模板
$res["content"] = $GLOBALS['tmpl']->fetch("article_show_comment.html"); //渲染模板,不输出但是接收模板内容(得到html块,用于替换主页面的分页div)
echo json_encode($res);
}

  3、模板文件【deal_show.html】

直接在原模板文件</body>之前加上ajax方法,用来翻页作用,代码如下:

<!-- ajax+php分页 -xzz5.11 -->
<script type="text/javascript">
$(function(){
var init_id = 1;     
index(init_id); //初始化页面 init_id==1
}); function index(id){
var id = id;
var deal_id = {$deal_info.id};
//把数据传递到要替换的控制器方法中,这里你还可以传入查询字段,比如phone,name等,后台通过【是否为空】来做过滤

$.ajax({
url:"/index.php?ctl=ajax&act=deal_show_comment",
type:"GET",
async:false,
dataType:"JSON",
data:{'p':id,'id':deal_id},  //把查询字段和值 通过这里传给后台ajax,实现多条件ajax查询分页
success:function(data){
//用get方法发送信息到ajax中的deal_show_comment方法
$("#pagination").replaceWith(data.content); //html块替换html的div
},
error:function(data){
console.log("4:ajax not run~");
}
});
}
</script>

  4、注意啦,你应该还有一个页面【article_show_comment.html】,就是php进行  $this->assign("list",$list);

  fetch()非常关键,获取的list和page数据渲染后的模板html文件,但是不输出,这里是关键点。====>>>>>>>>>>重中之重,fetch()的结果是:html块,用来替换deal_show.html的分页块

  我们的目的:把独立的【rticle_show_comment.html】文件,去替换【deal_show.html】文件里面的<div>,看好哦,是【deal_show.html】展示分页数据list和分页$page的<div>。 明白了这个你就成功一半了。

  使用TP的fetch()方法,在上面的ajaxModule.class.php的方法已经介绍了,在末尾部分,不懂自行查看TP手册fetch()

  这里就给出替换内容的article_show_comment.html(ajax动态生成DOM,原来的关联js无效,所以再次引入即可)。

<div id="pagination">
<div class="blank0"></div>
{foreach from=$list item=comment_item}
{include file="inc/comment_item_nolog.html"}   <!-- 这里的话,就是php另外引入的一个html文件,用来循环数据,在我的项目里他和下面的js有关联 -->
{/foreach}
<div class="blank0"></div>
<div class="pages">{$page}</div>
</div> <!-- 上面是动态生成的DOM,原html模板页面的关联js不生效,所以你没ajax调用一次,就需要引入一下js -->
<script type="text/javascript" src="{$TMPL}/js/deal_comment.js"></script>

  5、顺便提一下,ajaxModule.class.php和XXXXModule.class.php完全是不同的2个控制器(因为TP2.0版本控制器就是Module,你要是TP3.1以后的,可以看成是AjaxController.class.php 都可以的),一个用来返回ajax请求的结果,一个是普通的控制器。

 6、在最后,顺道感谢  小king哥,ThankU!

上一篇:第一部分:开发前的准备-第三章 Application 基本原理


下一篇:Django视图,与数据库交互并返回数据