datatables 实现后端分页搜索
安装 datatables
在你的项目中使用 DataTables,只需要引入三个文件即可,jQuery库,一个DT的核心js文件和一个DT的css文件
1 <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.21/css/jquery.dataTables.css"> 2 <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> 3 <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
HTML:
1 <table id="table_id_example" class="display"> 2 <thead> 3 <tr> 4 <th>ID</th> 5 <th>标题</th> 6 <th>作者</th> 7 <th>内容</th> 8 </tr> 9 </thead> 10 <tbody> 11 {volist name="data" id="val" } 12 <tr> 13 <td>{$val.id}</td> 14 <td>{$val.title}</td> 15 <td>{$val.name}</td> 16 <td>{$val.desn}</td> 17 </tr> 18 {/volist} 19 </tbody> 20 </table>
Script:
1 <script> 2 $(function () { 3 $('#table_id_example').DataTable({ 4 // 开启服务器模式 5 serverSide:true, 6 // 定义每页显示条数 7 lengthMenu: [ 5, 10, 15, 25, 100 ], 8 "ajax": 'http://localhost/coll5/over1/public/index.php/index/admin/paging', 9 "columns": [ 10 {"data": 'id'}, 11 {"data": 'title'}, 12 {"data": 'name'}, 13 {"data": 'desn'} 14 ] 15 }); 16 }) 17 </script>
PHP:
1 public function paging(Request $request){ 2 // 搜索的条件 3 $search = $request->get('search.value'); 4 // 分页开始的位置 5 $start = $request->get('start'); 6 // 分页结束的位置 7 $length = $request->get('length'); 8 // 条件存入缓存 9 Cache::store('redis')->set('search',$search); 10 // 取出条件 11 $where = Cache::store('redis')->get('search'); 12 // 分页查询 13 $data = Db::table('books')->where('title','like',"%$where%")->limit($start,$length)->select(); 14 // 高亮显示 15 foreach ($data as &$val){ 16 $val['title'] = str_replace($search,"<span style='color: red;font-weight: bold'>$search</span>",$val['title']); 17 } 18 // 返回数据 19 return json(['code' => 200,'msg' => '查询成功','data' => $data]); 20 }