Datatables front-end plug of use - Part II

We must first of its profits

This series of articles describes those handy front-end plug-ins I used in the operation and maintenance of the system development process, the article introduces the Datatables plug-in basic use of this article as a continuation of the previous one, and will introduce a number of senior Databases usage, such as getting data from different sources of data, modify data in the final presentation, operating Dom change the page function, open server data processing

Loading

table all the data in the previous article are rendered directly in html, datatables also supports several other data sources, in order to facilitate the achievement of a more flexible control

Acquired from the array

<table id="myTable-x" class="display" style="width:100%"></table>

$(document).ready(function() {
    var dataSet = [
      ["3","https://ops-coffee.cn","2018-07-03"],
      ["9","https://demo.ops-coffee.cn", "2019-08-06"],
    ];

    $('#myTable-x').DataTable({
        "data": dataSet,
        "columns": [
          { title: "Id" },
          { title: "Site" },
          { title: "Date" },
        ]
    })
});

data: the specified array

columns: Configuration title of each column

Note: obtaining data must have a header from the array, if not then may report the error below:

Uncaught TypeError: Cannot read property 'aDataSort' of undefined

The solution is to add datatables columnsconfiguration, or write on the table thead

<table id="myTable-x" class="display" style="width:100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Site</th>
            <th>Date</th>
        </tr>
    </thead>
</table>

Obtained from the object

<table id="myTable-x" class="display" style="width:100%"></table>

$(document).ready(function() {
    var dataSet = [
      {"Id":"3","Site":"https://ops-coffee.cn","Date":"2018-07-03"},
      {"Id":"9","Site":"https://demo.ops-coffee.cn","Date":"2019-08-06"},
    ];

    $('#myTable-x').DataTable({
        "data": dataSet,
        "columns": [
          {"data": "Id", "title": "Id"},
          {"data": "Site", "title": "Site"},
          {"data": "Date", "title": "Date"},
        ]
    })
});

Use an array of objects, be sure to configure the columns of datatelling DataTables corresponding attribute for each column, titleconfiguration options, add title will add a table header

Obtained from the examples

$(document).ready(function() {
    function dataSet(id, site, date) {
      this.id = id;
      this.site = site;
      this.date = date;
    };

    $('#myTable-x').dataTable({
      data: [
        new dataSet("3", "https://ops-coffee.cn", "2018-07-03"),
        new dataSet("9", "https://demo.ops-coffee.cn", "2019-08-06"),
      ],
      columns: [
          {"data": "id", "title":"Id"},
          {"data": "site", "title":"Site"},
          {"data": "date", "title":"Date"}
      ]
    });
});

Ajax asynchronous acquisition

Datatables also supports asynchronous Ajax way to load data, a simple way is to directly configure a url address to

$(document).ready(function() {
    $('#myTable-x').dataTable({
        "ajax": 'sdata.json'
    });
});

ajax received data may be an array or an object, note that columnsthe configuration may correspond to two formats described with reference to the pre-processed data

The results of data processing

Top of the table can be found in the content of a site column is a URL, how if we want to be able to click on the URL to achieve it? You can use columnsthe renderproperty to make changes to show results

$(document).ready(function() {
    $('#myTable-x').dataTable({
        "ajax": 'sdata.json',
        "columns": [
            {"data": "id", "title":"Id"},
            {
                "data": "site", 
                "title":"Site",
                "render": function (data, type, row) {
                  return '<a href='+data+' target="_blank">'+data+'</a>'
                }
            },
            {"data": "date", "title":"Date"}
        ]
    });
});

followed behind render functions, data tables whenever data needs to obtain a cell in the column of renderthe function will be executed, and the function may be executed multiple times, the default function of three parameters, namely mean:

data: Specific data cells, e.g.https://ops-coffee.cn

type: identifies the type of request that the first call, there will be filter, display, type,sort

row: Complete this line of data sources, if the object passed as Demo sample data, you can pass row.sitedata to get this line of site columns

After getting a series of processing parameters can be returnreturned eventually want to show content

Of course, by columnsthe end of the table to add a column to achieve edit, delete button display

"columns": [
    {"data": "id", "title":"Id"},
    {
        "data": "site", 
        "title":"Site",
        "render": function (data, type, row) {
          return '<a href='+data+' target="_blank">'+data+'</a>'
        }
    },  
    {"data": "date", "title":"Date"},
    {   
      "data": "id",
      "title": "操作",
      "render": function (data, type, row) {
        return '<a href="#update/'+row.id+'/" class="btn btn-warning btn-sm">编辑</a> ' +
               '<a href="#delete/'+row.id+'/" class="btn btn-danger btn-sm">删除</a>'
      } 
    }   
]

The final results are presented in the following figure

Dom operations

If I do not need datatables the upper left corner of the page shows the number of pieces of information, and to add a button to change into how to do it? Here can be achieved by means of datatables of dom

By default, the table will have the upper left corner of the page shows the number of pieces, searching the upper right corner, lower left corner of the table information, the lower right corner of the page, the middle of the table and wait for data to load itself, these are datatables the DOM, they actually div is wrapped in a select, input or the like html tags, each of the DOM are DataTables corresponds to a letter, their correspondence is as follows:

L: length, represents the upper-left corner of the page shows the number of controls

f: Filtering, represents the upper-right corner of the Search Control

t: the Table, the table represents itself

i: Information, on behalf of the lower left corner of the form information control

p: the lower right corner of the pagination, on behalf of the paging controls

r: Processing, represent the middle waiting for data loading prompt control

这些控件在datatables里可以通过配置dom来控制他们的显示位置,以及是否显示,默认的显示顺序是lfrtip

$('#myTable-x').dataTable({
    "dom": 'lfrtip'
})

你如果不想显示某个控件,可以通过去掉dom配置项里对应的字母实现,同时Datatables支持四个自定义的标签,通过这四个标签可以方便的来修改DOM的展示

< > 尖括号就代表html里的div

<"class"> 代表了添加了class的div

<"#id"> 代表了添加了id的div

<"#id.class"> 代表添加了id和class的div

我们想把右上角的每页显示条数控件换成添加按钮的话可以这样写

$('#myTable-x').dataTable({
    "dom": '<"#add-btn.toolbar">frtip'
})

$("#add-btn.toolbar").html(
  '<button href="#add" class="btn btn-success btn-sm"> + 添加</button>'
)

遇到样式问题,需要添加css

<style type="text/css">
  .toolbar {float:left}
</style>

这样就完美实现了

服务器端处理

Datatables支持使用服务端进行数据处理,当开启服务端数据处理后,Datatables将在页面执行分页、排序、搜索等操作时向服务端发出Ajax请求,Ajax请求会传递许多变量给服务端,服务端接收到请求后根据变量的值对数据进行处理,处理完成按照固定的格式返回给前端页面,页面对返回的数据进行渲染提供给用户查看

开启服务器模式只需要两个设置项serverSideajax

$('#myTable-x').dataTable({
    "serverSide": true,
    "processing": true,
    "ajax": '/api/site/data'
})

serverSide: 为true时表示开启服务端处理模式

processing: 为true时会开启数据处理中的提示,非必须

ajax: 指定服务器端的地址,可以像上边一样是个字符串,也可以像jQuery.ajax一样作为一个对象使用,例如我想传递额外的参数(datatables默认会给后端传递许多的参数,下边有讲)给后端服务器的话,可以这样用

$('#myTable-x').dataTable({
    "serverSide": true,
    "processing": true,
    "ajax": {
        "url": "/api/site/data",
        "data": function (d) {
            d.type = 'ops-coffee';
        }
    }
})

data: 可以在发送请求给后端时额外增加type=ops-coffee的参数

发送到服务器端的参数

当开启服务端数据处理后,默认会给服务端传递许多参数,大概如下:

draw:绘制计数器,主要用来确保Ajax从服务器端接收到的数据是对应同一次请求的
start:第一条数据的起始位置
length:每页显示的条数
search[value]:全局的检索关键字
order[i][column]:告诉服务器哪些列是需要排序的,i为排序列的序号,下边的i相同含义,注意i是从0开始的
order[i][dir]:告诉服务器排序的方式"desc","asc"
columns[i][data]:columns上定义的data属性值
columns[i][name]:columns上定义的name属性值
columns[i][searchable]:告诉服务器哪些列可以被搜索
columns[i][orderable]:告诉服务器哪些列可以进行排序
columns[i][search][value]:告诉服务器某些列的具体搜索条件

如果需要后台分页,那么需要拿到startlength两个参数做相应的处理,

如果有搜索的内容,那么需要拿到serch[value]参数做处理

服务端返回数据的格式

服务端需要返回datatables可以处理的数据格式,具体数据格式如下:

{
    "draw": 1,
    "recordsTotal": 7,
    "recordsFiltered": 7,
    "data": [
        {
            "id": 3,
            "site": "https://ops-coffee.cn",
            "date": "2018-07-03"
        },
        {
            "id": 9,
            "site": "https://demo.ops-coffee.cn",
            "date": "2019-08-06"
        }
        // 省略其他结果
    ]
}

draw: 客户端调用服务端次数标识,客户端传过来是什么原样返回回去即可,无需修改

recordsTotal: 数据总条数,没有过滤的数据总条数

recordsFiltered: 过滤后符合要求的条数,如果没有搜索参数那么这个值与recordsTotal一致

data: 需要显示的具体数据,json格式

API调用

Datatables提供了强大的API来处理表格上的数据,可以通过API添加数据到已经存在的表格,或者对已经存在的数据进行操作,API的类型非常丰富,详细的信息可以查阅官网,使用方法如下:

跳转到页

跳转到第3页:

var table = $('#myTable').DataTable()

table.page(2).draw(false)

page(2): page为分页方法,后边的2表示跳转到第几页,可以是一个数字,也可以是firstnextpreviouslast这样的字符串,当为数字时要从0算起,例如示例中为2实际上是跳转到了第3页

draw(false): 对表格进行重绘以实现表格更新的显示,大多数的api操作都不会直接更新在页面上,所以需要调用下draw,默认情况下重绘后分页会被重置回到第一页,当设置为false时分页不会被重置

搜索某列

搜索第2列包含https://ops-coffee.cn的行

var tablx = $('#myTable').dataTable()

tablx.api().column(1).search('https://ops-coffee.cn').draw()

首先需要注意这个例子中的API调用使用了.api(),这是因为上一个例子在初始化时用了.DataTable()而这个例子初始化时用了.dataTable(),仅仅是d字母大小写的区别而已,但意义确不同,前者直接返回API实例,后者返回的是jQuery实例

完整Demo

为了方便大家学习,我写了个完整的demo,你可以在线查看效果或下载代码应用到自己的项目中

在线Demo地址:https://demo.ops-coffee.cn/datatables/

Github源码地址:https://github.com/ops-coffee/demo/tree/master/datatables


扫码关注公众号查看更多实用文章

相关文章推荐阅读:

Guess you like

Origin www.cnblogs.com/37Y37/p/11350164.html