改造thinkphp 的 Page类,使其支持ajax方式

jerry thinkphp 2015年11月19日 收藏
改造thinkphp 的 Page类,使其支持ajax方式
效果:

说明:thinkphp版本:3.2.1
步骤:
1、打开Page.class.php(路径:ThinkPHP/Library/Think)
找到第48行:
  1.  empty($_GET[$this->p]) ? 1 : intval($_GET[$this->p]); 
改为:
  1.  empty(I($this->p)) ? 1 : intval(I($this->p));

实际是改为用内置的 I 函数读取传递进来的P参数,这样并不会影响原有的功能。

2、ajax方式的调用:
即前台html页面
  1. <div id="rs">此处用来显示分页内容</div><br class="clear" /><br />
javascript:
  1.     function jzry(p) {
  2.         var request = $.ajax({
  3.             url: "__MODULE__/Home/jzrh",  //用ajax加载分页数据
  4.             type: "POST",
  5.             async: false,
  6.             data:{p:p},
  7.             beforeSend: function(xhr) {
  8.                 $('#message').html("正在加载数据,请稍候。");
  9.             }
  10.         });
  11.         request.done(function(msg) {
  12.             if (msg.bj == 'ok') {
  13.                 $('#rs').html(msg.page);    //显示分页
  14.                 $("#rs a").removeAttr("href");   //删除原来的连接地址方式,
  15.                 
  16.                 //改用ajax按键事件
  17.                 $(".num,.end,.first").on("click", function(){
  18.                     jzry( $(this).text() );
  19.                 });
  20.                 $(".next").on("click", function(){
  21.                     jzry( parseInt($(".current").text())+1);
  22.                 });
  23.                 $(".prev").on("click", function(){
  24.                     jzry( parseInt($(".current").text())-1);
  25.                 });
  26.         }});
  27.         request.fail(function(jqXHR, textStatus) {
  28.             $('#message').html("错误: " + textStatus);
  29.         });
  30.     }
样式:
  1. <style>
  2. #rs a { color:#333;display:block; padding:0px 6px;
  3.            font-weight:bold;float:left;border:1px solid #5d9cdf;
  4.            height:20px; line-height:20px; margin:0px 2px;}
  5. .current { background:#a9d2ff; display:block; padding:0px 6px;
  6.                font-weight:bold;;float:left}
  7. .clear{clear:both}
  8. </style>

3、后台使用和原来的一样
  1.  
  2.         $user = M("user"); 
  3.         $User = $user->page($_POST['p'].',20')->order('id')->select();
  4.         if ($User > 0) {
  5.             $val['bj'] = 'ok';
  6.             $count=$user->count();
  7.             $Page=new \Think\Page($count,20);
  8.             $val['page']=$Page->show();
  9.             $this->ajaxReturn($val);                      //ajax方式返回
  10.         }