欢迎光临
我们一直在努力

DataTables 入门

先看一下效果

GITHUB:https://github.com/DataTables/DataTables#

引入 CSS 和 JS

 <!-- Datatables -->
    <link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">

 

 <!-- Datatables -->
    <script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
    <script src="/vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
    <script src="/vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script>
    <script src="/vendors/datatables.net-buttons/js/buttons.flash.min.js"></script>
    <script src="/vendors/datatables.net-buttons/js/buttons.html5.min.js"></script>
    <script src="/vendors/datatables.net-buttons/js/buttons.print.min.js"></script>
    <script src="/vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script>
    <script src="/vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
    <script src="/vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="/vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
    <script src="/vendors/datatables.net-scroller/js/dataTables.scroller.min.js"></script>
    <script src="/vendors/jszip/dist/jszip.min.js"></script>
    <script src="/vendors/pdfmake/build/pdfmake.min.js"></script>
    <script src="/vendors/pdfmake/build/vfs_fonts.js"></script>

 

<table id="datatable_list" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">

 

我们为了方便修改datatables的属性所以我们单独定义出来

 $.dataTablesSettings = {
            "dom": "Bfrtip",
            "bAutoWidth": false,
            "bDeferRender": true,
            "bLengthChange": true,
            "bPaginate": true,
            "bServerSide": true,
            "bSort": true,
            "buttons": [ //这个是她带给你的一些功能按键... 
                {
                    "extend": "copy",
                    "className": "btn-sm"
                },
                {
                    "extend": "csv",
                    "className": "btn-sm"
                },
                {
                    "extend": "excel",
                    "className": "btn-sm"
                },
                {
                    "extend": "pdfHtml5",
                    "className": "btn-sm"
                },
                {
                    "extend": "print",
                    "className": "btn-sm"
                },
                {
                    "extend": "pdf",
                    "className": "btn-sm"
                }
            ],
            "searching": false, //默认搜索框
            "ordering": true,
            "responsive": true,
            "paginate": true,
            "processing": true,
            "serverSide": true,
            "ajax": "https://后端接口的地址",
            "dataSrc": 'data',
            "aaSorting": [[0, 'desc']], //根据 columns 字段的 键位 0 , desc 倒序
            "pageLength": 50, //分页数量
            "stateSave": false,
            "columns": [ //字段列们
                {
                    "title": "ID", "data": "id", 'name': 'id' 
                },
                {
                    "title": "时间",  //标题
                    "data": "created_at",   //服务端数据
                    'name': 'created_at',   //别名
                    "render": function (data, type, row) { //如果有需求对返回数据的处理
                        if (data === undefined) { //如果是 undefined -,- 不介绍
                            return '未知';    //返回想展示出来的文字
                        }
                            //可以对(data)做你想做的事情 ......

                        return data;  //返回她
                    }
                },
                {
                  "title": "操作", 
                  "data": 'id', 
                  'name': 'operation', 
                  "render": function (data, type, row) {
                    return "<a href='详情页地址" + data + "'>查看详情</a>";
                }
            ],
            "language": { //自定义描述....
                "sProcessing": "正在获取数据, 请稍后...",
                "sLengthMenu": "显示 _MEUN_ 条",
                "sZeroRecords": "没有找到数据",
                "sInfo": "从 _START_ 到 _END_ 条记录 总记录数为 _TOTAL_ 条",
                "sInfoEmpty": "记录数为0",
                "sInfoFiltered": "(全部记录数 _MAX_ 条)",
                "sInfoPostFix": "",
                "sSearch": "全局搜索",
                "sUry": "",
                "oPaginate": {
                    "sFirst": "第一页",
                    "sPrevious": "上一页",
                    "sNext": "下一页",
                    "sLast": "最后一页"
                },
                "loadingRecords": "Please wait - loading...",
                "processing": "DataTables is currently busy",
                "search": "Apply filter _INPUT_ to table"
            },
            "fnServerParams": function (aoData) { //这个里面的 aoData就是会发送到后端的数据
              //在这里 你可以对 发送到后端之前做任何事情. 
                aoData._rand = Math.random();
            },
            "fnDrawCallback": function () {

            }
        };

 

如果我们想更改分页数的显示

 //分页数设置
        $('.pages_num').click(function () {
           //修改 pageLength 的值
            $.dataTablesSettings.pageLength = $(this).attr('describe');
           //$(this).attr('describe') 等于 你想要设置的每页展示条数

            dataTable.fnDestroy(false); //我们要重建它
            dataTable = $("#datatable_list").dataTable($.dataTablesSettings);
        });

//至于页码什么的前端都搞好了不用再管啦....

自定义搜索

//$.dataTablesSettings.fnServerParams 我们在发送之前可以做任何事情
$.dataTablesSettings.fnServerParams = function (aoData) {
  //aoData 在介绍一遍 这个是发送之前的数据

                aoData._rand = Math.random();

                //虽然里面有 search 这个数据 但是发现不给她 赋值成空的 [] 才能 push
                aoData.search = [];

                aoData.search.push(
                    //自定义搜索
                    {
                        "name": "search_input",
                        "value": $('#search_input').val(),
                        "regex": false
                      //里面可以在加一些你想要的 键值对
                    },
                    //开始时间
                    {
                        "name": "search_start_time",
                        "value": $('input[name=daterangepicker_start]').val(),
                        "regex": false
                    },
                    //结束时间
                    {
                        "name": "search_end_time",
                        "value": $('input[name=daterangepicker_end]').val(),
                        "regex": false
                    }
                );
            };

            //搜索就是设置参数,然后销毁datatable重新再建一个
            dataTable.fnDestroy(false);
            dataTable = $("#datatable_list").dataTable($.dataTablesSettings);
            //搜索后跳转到第一页 这个基本上不用 应为 默认就是会 回到第一页的....
            //dataTable.fnPageChange(0);

 

请求到后台的数据

draw:0
columns[0][data]:id
columns[0][name]:id
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:created_at
columns[1][name]:created_at
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
order[0][column]:0
order[0][dir]:desc
start:0
length:50
search[0][name]:search_input
search[0][value]:
search[0][regex]:false
search[1][name]:search_start_time
search[1][value]:2017-08-24 10:06:08
search[1][regex]:false
search[2][name]:search_end_time
search[2][value]:2017-09-22 10:06:08
search[2][regex]:false
search[3][name]:search_module_rule_const
search[3][value]:
search[3][regex]:false
search[4][name]:search_pay_states
search[4][value]:
search[4][regex]:false
search[5][name]:serch_monery
search[5][value]:0;100000000
search[5][regex]:false
_rand:0.5223628085815641
_:1506045968347

 

后台返回数据#

{
    "draw":"1",
    "recordsTotal":65,
    "recordsFiltered":65,
    "data":[
        {
            "id":91679,
            "created_at":"2017-08-28 10:25:07"
            }
        }
    ]
}

 

附赠一个时间控件的操作 daterangepicker#

GITHUB:https://github.com/sensortower/daterangepicker#

 <!-- bootstrap-daterangepicker -->
    <link href="/vendors/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet">
    <!-- bootstrap-datetimepicker -->
    <link href="/vendors/bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css" rel="stylesheet">

 

 <!-- bootstrap-daterangepicker -->
    <script src="/vendors/moment/min/moment.min.js"></script>
    <script src="/vendors/bootstrap-daterangepicker/daterangepicker.js"></script>
    <!-- bootstrap-datetimepicker -->
    <script src="/vendors/bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>

 

 //时间搜索框
        $('#search_time').daterangepicker({
            timePicker: true,
            timePickerIncrement: 5,
            showDropdowns: true,
            showWeekNumbers: true,
            timePicker24Hour: true,
            format: 'YYYY-MM-DD HH:mm:ss',
            language: 'CN',
            ranges: { 
                '今天': [moment(), moment()],
                '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                '7天前': [moment().subtract(6, 'days'), moment()],
                '30天前': [moment().subtract(29, 'days'), moment()],
                '这个月': [moment().startOf('month'), moment().endOf('month')],
                '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            opens: 'left',
            buttonClasses: ['btn btn-default'],
            applyClass: 'btn-small btn-primary',
            cancelClass: 'btn-small',
            alwaysShowCalendars: true,
            locale: {
                applyLabel: '确认',
                cancelLabel: '清除',
                format: 'YYYY-MM-DD HH:mm:ss',
                toLabel: 'To',
                separator: ' 至 ',
                customRangeLabel: '自定义',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                firstDay: 1
            }
        });
赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » DataTables 入门

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址