Explore the road of jquery.dataTables - server configuration page

Recent data have nothing else wanted to study under the table, because before contact form layui and bootstrap data, in line with how much learning attitude can learn how to learn, learning side paging service under dataTables configuration. Share a special problem which encountered and solutions with the students.

 

With slightly different bootstrap data table, in addition to the introduction of the necessary associated js DOM node ( < Table ID = "Table" class = "Table Table Table-hover-responsive" > </ Table > ), we also need an outer header parts, as is the entire table are available through bootstrap js rendering, while the header section dataTables need to add our own pages, as follows:

                            < Table ID = "Table" class = "Table Table-responsive Table-hover" > 
                                < thead > 
                                    < TR > 
                                        < TH > ID </ TH > 
                                        < TH > File name </ TH > 
                                        < TH > File Type </ TH > 
                                        < TH > logical address </ TH > 
                                        < TH > physical address </ TH > 
                                        < TH >Updated </ TH> 
                                        < TH > updated </ TH > 
                                    </ TR > 
                                </ thead > 
                            </ Table >
                                        

 

I thought dataTable side paging service will be like bootstrap, like, give him a bunch of url, and the rest to him, so I wrote the following code that initializes the table:

<script type="text/javascript" src="static/assets/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="static/assets/libs/datatablejs/jquery.dataTables.min.js"></script>
<script type="text/javascript">
    initTable();

    function initTable () {
         var Language = { "sProcessing": "Processing ...", "sLengthMenu": "Show _MENU_ results", "sZeroRecords": "there are no matching", "sInfo": "Present _START_ to _END_ records, total _TOTAL_ article "," sInfoEmpty ":" Showing page 0-0 results were 0 "," sInfoFiltered ":" (co _MAX_ page) "," sInfoPostFix ":" "," sSearch ":" search: "," sUrl ":" "," sEmptyTable ":" data in the table is empty "," sLoadingRecords ":" Loading ... "," sInfoThousands ":" , " , "oPaginate": { "sFirst ": " Home", "sPrevious": "page", "sNext": "next page", "sLast": "last" }};
        $ ( '#Table' ) .DataTable ({
             'Processing': to true ,
             'pageLength':. 5, // page shows the number of 
            'Ajax': '/ ADMIN / File / List', // asynchronous request address 
            ' lengthChange ': to false ,
             ' Searching ': to false ,
             ' info ': to true ,
             ' autoWidth ': to false , // automatically column width 
            Language: Language, // international 
            columns: [{
                Data: "ID" // Binding background data column zodiac 
            }, {
                data: "filename"
            }, {
                data: 'filetype',
                defaultContent: "" // Default 
            }, {
                data: 'logicadress',
                defaultContent: ""
            }, {
                data: 'physicsadress',
                defaultContent: ""
            }, {
                data: 'modifyUser',
                defaultContent: "-"
            }, {
                data: 'modifyTime',
                defaultContent: ""
            }],
            columnDefs: [{ // custom first column box 
                Targets: [0], // first of several columns: the default starting from 0 
                orderable: false , // whether to support sorting 
                the render: function (the above mentioned id, of the type, Row, Meta) {
                     return '<INPUT type = "CheckBox" name = "IDS" value =' + ID + '> <label for = "input-' + ID + '"> </ label>' ;
                }
            }]
        })
    }
</script>

Refresh the page results are as follows:












what! ! What my data go? Is request addition to the problem?

View the console, no problem background data discovery request also received normally.

By the way, the server returns data format issue! ! Background data returned is custom JSON, the default values ​​do not meet the specifications of dataTables! !

{"code":"200",
"msg":null,
"data":{
      "count":7,
      "totalPage":2,
      "pageSize":5,
      "currentPage":1,
      "list":[
            {"createUser":null,"createTime":"2019-05-28T14:24:56.000+0000","modifyUser":10000001,"modifyTime":"2019-05-09T14:24:59.000+0000","id":7,"filename":"女王大人","filetype":3,"logicadress":"www","physicsadress":"E:/test.txt","sort":"99"},
            {"createUser":null,"createTime":"2019-05-28T14:24:54.000+0000","modifyUser":10000001,"modifyTime":"2019-05-08T14:25:02.000+0000","id":6,"filename":"你的皇帝","filetype":2,"logicadress":"www","physicsadress":"E:/test.txt","sort":"99"},
            {"createUser":null,"createTime":"2019-05-28T14:24:51.000+0000","modifyUser":10000001,"modifyTime":"2019-05-07T14:25:04.000+0000","id":5,"filename":"阿里斯嘉","filetype":0,"logicadress":"www","physicsadress":"E:/test.txt","sort":"99"},
            {"createUser":null,"createTime":"2019-05-28T14:24:49.000+0000","modifyUser":10000001,"modifyTime":"2019-05-06T14:25:07.000+0000","id":4,"filename":"马大哈","filetype":1,"logicadress":"www","physicsadress":"E:/test.txt","sort":"99"},
            {"createUser":null,"createTime":"2019-05-28T14:24:46.000+0000","modifyUser":10000001,"modifyTime":"2019-05-05T14:25:09.000+0000","id":3,"filename":"土豆司","filetype":1,"logicadress":"www","physicsadress":"E:/test.txt","sort":"99"}
          ],
      "sort":null,
      "order":null
     }
}

I returned it encapsulates the data on the server, resulting in dataTables do not know where to start!

After finding the problem, with one hundred teachers of various blog I found a solution: transform 'ajax' property

$('#table').DataTable({
            ...
            'ajax': {
                url: '/admin/file/list',
                the dataSrc: function (JSON) {
                     return json.data.list; // the specified data string to return the position, the data as an array 
                }
            },
            ...
 })

By specifying the location of data columns can be achieved on a background custom data rendering (which would normally return data to ensure uniform format):

Refresh the page to display the data again normal

Ah, very satisfied. . But the new problem has emerged: Paging something wrong, and then view the console I found a total of seven records, and normally should be 2 7

Blog by a large number of one hundred teachers, found the problem: Not open side paging service! !

Continue to transform as follows:

$('#table').DataTable({
            ...
            'Serverside': to true ,      // turn on the service side paging 
            ...
 )}

Refresh the page again, accidents, and very suddenly:

The emergence of unexpected things: after opening the real side paging service, and lost my data! !

This is the background error, the console can be found in the open-side paging service, dataTables a lot of parameters passed to the background initialization:

You can see behind url stitching a series of strings, resulting in the background SpringMVC there is a problem in the package parameters:

    @GetMapping("file/list")
    public RestJson page(PageHelper pageHelper) {
        System.out.println(pageHelper);
        RestJson json = fileRecordService.getFileRecordByPage(pageHelper);
        return json;
    }

PageHelper I pagination tools to customize the specific code as follows:

public class PageHelper<T> implements Serializable {

    private Integer count;//总记录数
    private Integer totalPage;//总页数
    private Integer pageSize;//每页显示的条数
    private Integer currentPage;//当前页
    private List<T> list = new ArrayList<T>();//分页之后的数据
    private String sort;//排序字段
    private String order;//升序或降序

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getPageSize() {
        return this.pageSize == null ? 5 : this.pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getCurrentPage() {
        return this.currentPage == null ? 1 : this.currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public String getSort() {
        return this.sort == "" ? null : this.sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrder() {
        return this.order == "" ? null : this.order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    /**
     * 计算总页数
     *
     * @return 总页数
     */
    public int countPage() {
        int countPage = getCount() / getPageSize();
        return getCount() % getPageSize() == 0 ? countPage : countPage + 1;
    }

    /**
     * 从哪条开始取(当前记录数)
     *
     * @return 当前记录数
     */
    public int countOffSet() {
        return getPageSize() * (getCurrentPage() - 1);
    }

    /**
     * MYSQL
     * 取几条
     *
     * @return 取几条
     */
    public int countMySQLLength() {
        return getPageSize();
    }

    /**
     * ORACLE
     * 取几条
     *
     * @return 取几条
     */
    public int countOracleLength() {
        return getPageSize() * getCurrentPage();
    }

    @Override
    public String toString() {
        return "[ " +
                "count:" + count +
                " totalPage:" + totalPage +
                " pageSize:" + pageSize +
                " currentPage:" + currentPage +
                " sort:" + sort +
                " order:" + order +
                " ]";
    }
}

由于SpringMVC封装参数时出现了问题,于是我想能不能在dataTables初始化时自定义后台传递的参数呢?

继续改造‘ajax’属性:

$('#table').DataTable({
           ...
            'ajax': {
                url: '/admin/file/list', // url请求
                data: function (data) { // 定义初始化参数 :data为向后台发送的参数obj
                    return $.extend( {},{}, { //自定义参数
                        "currentPage": data.start/data.length+1, //当前页"pageSize": data.length, // 每页显示条数,data.length='pageLength'属性的值 我设置的是5
                    } )
                },
                dataSrc: function (json) {
                    return json.data.list;
                }
            },
            ...
 )}    

再次刷新页面,数据又回来了

等等,分页是怎么回事??不打紧,加上这两句:

 $('#table').DataTable({
            ...
            'ajax': {
                ...
                dataSrc: function (json) {
                    json.recordsFiltered = json.data.count;  // 指定记录数
                    json.recordsTotal = json.data.totalPage; // 指定页数
                    return json.data.list;
                }
            },
            ...
 })

再次刷新页面出现了预期的结果:

调试完毕,发现部分列不应该排序,查看‘columnDefs’属性,发现ID列排序被禁用,但排序图标初始化时依然存在。

添加如下属性:

$('#table').DataTable({
            ...
            'order': [1,'asc'], //修改默认的排序列为第2列、升序
            ...
 })

再次刷新页面后正常显示,能不能实现指定列排序呢?

修改代码如下(为了使代码更简洁我将‘columnDefs’属性中的代码转移到‘columns’属性中):

$('#table').DataTable({
            ...
            columns:[{  // 合并后的columns
                data: "id", // 绑定后台数据列的属性
                sortable: false, // 禁止排序
                render : function(id, type, row, meta) { // 将数据进行DOM转换
                    return '<input type="checkbox" name="ids" value=' + id + '><label for="input-' + id + '"></label>';
                }
            },{
                data: "filename",
                render : function(id) {
                    return '<a href="javascript:;">'+id+'<a/>';
                }
            },{
                data: 'filetype',
                defaultContent : "",
                sortable: false,
            },{
                data: 'logicadress',
                defaultContent : "",
                sortable: false,
            },{
                data: 'physicsadress',
                defaultContent : "",
                sortable: false,
            },{
                data: 'modifyUser',
                defaultContent : "-",
                sortable: false,
            },{
                data: 'modifyTime',
                defaultContent : ""
            }],
       ... })

刷新页面后效果如下:

点击排序发现没有反应。后台的排序已经实现了,前台只要发送相应的参数即可。

继续修改代码如下:

$('#table').DataTable({
            ...
            'ajax': {
                ...
                data: function (data) {
                    console.log(data);
                    return $.extend( {},{}, {
                        "currentPage": data.start/data.length+1,
                        "pageSize": data.length,
                        "order": data.order[0].dir, //升序或降序:随鼠标点击发生变化
                        "sort": data.order[0].column==1?"fileName":"modifyTime" //获取排序列:下标从0开始,1代表第二列(因为只有两列参与排序,所以简单写了)
                    } )
                },
                ...
            },
            ...
 })

刷新页面,打开控制台,我们看下‘data’的结构:

{
  "draw": 1,
  "columns": [
    {
      "data": "id","name": "","searchable": true,"orderable": false,
      "search": {"value": "", "regex": false}
    },
    ...
  ],
  "order": [{"column": 1,"dir": "asc"}],
  "start": 0,
  "length": 5,
  "search": {"value": "","regex": false}
}

一个标准的json对象,现在回头看看这两行代码是不是有种恍然大悟的感觉:

"order": data.order[0].dir, 
"sort": data.order[0].column==1?"fileName":"modifyTime"

后台的分页和排序代码无须赘述,本文主要是分享在使用dataTables时如何自定义前后台参数问题,其实使用起来和bootstrap的数据表格有很多相似的地方,感觉还是后者更简单一些。咸鱼水平,不足之处欢迎指正!

Guess you like

Origin www.cnblogs.com/wangwz2019/p/11011264.html