Datatables使用教程

Datatables中文网手册:http://datatables.club/manual/install.html

可从网站上下载 datatables安装包,将其解压到你的pubic目录下,可以引入线上的 dataTables 来进行使用
laraver框架中使用示例代码
1.简单使用



<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
 

<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js">script>
 

<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.21/js/jquery.dataTables.js">script>


    
    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    script>
    
    <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.21/js/jquery.dataTables.js">script>

一个完整的示例


<html>
<head>
    <meta charset="utf-8">
    <title>DataTablestitle>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js">script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js">script>

    <link rel="stylesheet" type="text/css" href="/DataTables/media/css/jquery.dataTables.css">
    
    <script type="text/javascript" charset="utf8" src="/DataTables/media/js/jquery.js">script>
    
    <script type="text/javascript" charset="utf8" src="/DataTables/media/js/jquery.dataTables.js">script>
head>
<body>

<table id="table_id_example" class="display">
    <thead>
    <tr>
        <th>IDth>
        <th>标题th>
        <th>图片th>
        <th>阅读数th>
        <th>内容th>
        <th>插入时间th>
        <th>修改时间th>
    tr>
    thead>
    <tbody>

    @foreach($data as $v)
    <tr>
        <td>{{$v->id}}td>
        <td>{{$v->title}}td>
        <td>{{$v->image}}td>
        <td>{{$v->readnum}}td>
        <td>{{$v->cont}}td>
        <td>{{$v->deleted_at}}td>
        <td>{{$v->created_at}}td>

    tr>
    @endforeach

    tbody>
table>

body>

html>
<script>
    $(document).ready( function () {
        $('#table_id_example').DataTable();
    });
script>

控制器查询数据返回页面循环输出

 public function show(){
        $data=Article::get();
        return view('show',['data'=>$data]);
    }

laraver框架中使用示例代码,后端实现分页
html代码伪代码

<div class="page-container"><form method="get" onsubmit="return search()">
        @csrf
    <div class="text-c"> 日期范围:
        <input type="text" onfocus="WdatePicker({ maxDate:'#F{$dp.$D(\'datemax\')||\'%y-%M-%d\'}' })" id="datemin" class="input-text Wdate" style="width:120px;" name="datemin">
        -
        <input type="text" onfocus="WdatePicker({ minDate:'#F{$dp.$D(\'datemin\')}',maxDate:'%y-%M-%d' })" id="datemax" class="input-text Wdate" style="width:120px;" name="datemax">
        <input type="text" class="input-text" style="width:250px" placeholder="输入文章标题" id="title" name="title" value="">
        <button type="submit" class="btn btn-success " id="" name=""><i class="Hui-iconfont">i> 搜索button>
    div>
    form>
    <div class="cl pd-5 bg-1 bk-gray mt-20"> <span class="l"><a href="javascript:;" onclick="datadel()" class="btn btn-danger radius"><i class="Hui-iconfont">i> 批量删除a> <a href="{{route('admin.article.create')}}"  class="btn btn-primary radius"><i class="Hui-iconfont">i> 添加文章a>span> <span class="r">共有数据:<strong>strong>span> div>
    <table class="table table-border table-bordered table-bg">
        <thead>
        <tr>
            <th scope="col" colspan="9">文章列表th>
        tr>
        <tr class="text-c">
{{--            <th width="25"><input type="checkbox" name="" value="">th>--}}
            <th width="40">IDth>
            <th width="90">文章标题th>
            <th width="50">作者th>
            <th width="130">文章摘要th>
            <th width="150">文章封面th>
            <th width="130">加入时间th>
            <th width="150">操作th>
        tr>
        thead>
        <tbody>

        tbody>
    table>
div>
<script type="text/javascript" src="/admin/lib/My97DatePicker/4.8/WdatePicker.js">script>
<script type="text/javascript" src="/admin/lib/datatables/1.10.0/jquery.dataTables.min.js">script>
<script type="text/javascript" src="/admin/lib/laypage/1.2/laypage.js">script>
<script type="text/javascript">
     //表单提交
       function search(){
           //手动调用一次ajax
           dataTable.ajax.reload();
           //取消表单默认行为
           return false;
       }

     var dataTable= $('.table-bg').DataTable({
            //分页数量
            lengthMenu:[5,10,20],
            //隐藏搜索
            searching:false,
            columnDefs:[
                //索引第一列不进行排序
                {targets:[0,6],orderable: false}
            ],
            //开启服务器端分页  使用ajax
            serverSide:true,
            //进行ajax请求
            ajax:{
                type:"get",
                //设置请求的地址
                url: "{{route('admin.article.index')}}",
                data:function (ret) {
                    ret.datemin=$("#datemin").val()
                    ret.datemax=$("#datemax").val()
                    ret.title=$("#title").val()
                }
        },
            // 指定每一累显示的数据
            columns:[
                {'data':'id','className':'text-c'},
                {'data':'title','className':'text-c'},
                {'data':'author','className':'text-c'},
                {'data':'desn','className':'text-c'},
                {'data':'pic','className':'text-c'},
                {'data':'created_at','className':'text-c'},
                {'data':'btn','className':'text-c'},
            ]

        });
       dataTable.on('draw',function () {
           $(".label-danger").click(function () {
               //获取url地址
               url= $(this).attr('href')
               //发送ajax
               $.ajax({
                   url,
                   type: "DELETE",
                   dataTable:'json',
                   data:{_token:"{{csrf_token()}}"},
               }).then((res)=>{
                   if (res.code==200){
                       layer.confirm('删除成功', {
                           btn: ['好'] //按钮
                       }, function(){
                           layer.msg("提示", {icon: 1});
                           location.reload()
                       }, function(){
                           layer.msg('提示');
                       });
                   }
               })
               //禁止跳转
               return false;

           })

       })

script>

控制器代码

public function index(Request $request)
    {
        //判断是否我ajax请求
      if ($request->ajax()){
          //获取起始的位置
          $start=$request->get('start')?: 0;
          $query=Article::where('id','>',0);
          //结收要搜索的内容
          //搜索关键字
          $title=$request->get('title');
          //搜索的开始时间
          $datemin=$request->get('datemin');
          //搜索的结束时间
          $datemax=$request->get('datemax');
          //如果有搜索的标题名时
          if (!empty($title)){
              $query=$query->where('title','like',"%$title%");
          }
          //按时间段搜索
          if (!empty($datemax) && !empty($datemin)){
              $query=$query->whereBetween('created_at', [$datemin, $datemax]);
          }

          //获取点击的排序列是第几列
           $ordercolumns=$request->get('order')[0]['column'];
         //获取这一列的名称
           $ordername=$request->get('columns')[$ordercolumns]['data'];
          //获取排序的方式 升序 or 降序
           $ordertyp=$request->get('order')[0]['dir'];
           $query=$query->orderBy($ordername,$ordertyp);

            //获取记录数
            $count=$query->count();
            //获取每页显示的条数
            $length=min(100,$request->get('length',10));
            //分页查询数据
            $data=$query->offset($start)->limit($length)->get();
            $result=[
                //客户端调用服务器的次数
                'draw'=>$request->get($request->get('draw')),
                //获取数据的总条数
                'recordsTotal'=>$count,
                //数据过滤后的总数量
                'recordsFiltered'=>$count,
                //查询到的具体数据
                'data'=>$data,
            ];
            return $result;
        }
        return view('admin.article.index');
    }

TP框架中使用,原理一样,简单伪代码示例

html伪代码示例 引入方法一样

<body>
<table id="table_id_example" class="display">
    <thead>
    <tr>
        <th> idth>
        <th>标题th>
        <th>内容th>
        <th>独数th>
        <th>赞数th>
    tr>
    thead>
    <tbody>
    {volist name="data" id="vo"}
    <tr>
        <td>{$vo.id}td>
        <td>{$vo.title}td>
        <td>{$vo.content}td>
        <td>{$vo.read}td>
        <td>{$vo.zan}td>
    tr>
    {/volist}
    tbody>
table>

body>

<script>
    $(document).ready( function () {
        $('#table_id_example').DataTable({
            //开启服务器模式
            serverSide:true,
            //设置每页显示的条数
            lengMenu:[5,10],
            ajax:"http://www.shili.com/index.php/databast/index/indexs",
            "columns":[
                {'data':"id"},
                {'data':"title"},
                {'data':"content"},
                {'data':"read"},
                {'data':"zan"},  
            ]
        });

    } );
script>

控制器代码示例

public function index()
    {
        //查询数据  渲染视图
        $data=Db::table('article')->select();
        return view('index',compact('data'));

    }

    public function indexs(Request $request){
        //搜索的条件
        $search=$request->get('search.value');
        //后端分页的开始位置
        $start=$request->get('start');
        //lengt 后端分页结束的位置
        $length=$request->get('length');
        
        //搜索数据
        $data=Db::table('article')->where('title','like',"%$search%")->limit($start,$length)->select();
        
        //查询出数据存入redis中
       Cache::store('redis')->set('data',$data);
        //取出redis中存储的搜索条件
       Cache::store('redis')->get('data',$data);
        //条件高亮显示
        foreach ($data as $key=>&$val){
            $val['title'] =str_replace($search,"$search",$val['title']);
        }

        return json(['code'=>200,'msg'=>'查询成功','data'=>$data]);
    }

你可能感兴趣的:(php,php)