ThinkPHP5.1+Ajax实现的无刷新分页功能示例(2)

因为lst.html把列表摘了出来,所以还要在引入回去,才能使页面完整,同时,为了方便进行jquery操作,把列表用带id的div包裹起来:

<div id="paginate">
    {include file="selfattribute/paginate1"}
</div>

ThinkPHP5.1带的分页类使用的是BootStrap样式,它在页面显示时实际会有一个pagination的类,查看源代码如下:

<ul class="pagination">
  <li class="disabled">
    <span>&laquo;</span></li>
  <li class="active">
    <span>1</span></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=2" rel="external nofollow" rel="external nofollow" >2</a></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=3" rel="external nofollow" >3</a></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=4" rel="external nofollow" >4</a></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=5" rel="external nofollow" >5</a></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=6" rel="external nofollow" >6</a></li>
  <li>
    <a href="/xkershouche/public/admin/selfattribute/lst.html?page=2" rel="external nofollow" rel="external nofollow" >&raquo;</a></li>
</ul>

这就是好多人搞不懂的pagination是怎么来的。

然后开始写js代码,因为我们的分页按钮也在被请求的页面当中,属于“未来”的元素,所以这里我们要用on方法,这个方法是jquery1.7以后的方法,注意自己的jquery版本。

<script type="text/javascript">
  $(document).on('click', '.pagination a', function(event) {
    var url = $(this).attr('href');
    $.ajax({
      url: url,
      type: 'get',
    })
    .done(function(data) {
      $("#paginate").html(data);
    })
    return false;
  });
  </script>

其中.done()方法和success方法是一样的,return false是为了阻止默认事件,防止直接跳转。

那么服务器端就可以根据情况渲染模板了,代码如下:

public function lst()
  {
    $selfattribute_select = db("selfattribute")->paginate(5);
    $this->assign("self",$selfattribute_select);
    if (request()->isAjax()) {
      return view("paginate1");
    } else {
      return view();
    }
  }

更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。