To do a good job, he must sharpen his tools

This series of articles introduces the front-end plug-ins I used in the development process of operation and maintenance system. The last article introduced the basic use of Datatables plug-in. As a continuation of the last article, this article will introduce some advanced uses of Databases. For example, obtaining data from different data sources, modifying the final presentation of data, manipulating Dom to change page functions, and enabling server-side data processing, etc

The data load

All of the data in the previous article was directly rendered table data in HTML, and Datatables also support several other data sources for more flexible control

Get from an 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"}]})});Copy the code

Data: Specifies an array

Columns: Sets the title of each column

Note: When retrieving data from an array, you must have a table header. If you do not have a table header, the following error may occur:

Uncaught TypeError: Cannot read property 'aDataSort' of undefined
Copy the code

The solution is to add columns to the datatables or write thead of the table

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

Gets from an 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"}]})});Copy the code

To use an array of objects, you must configure the data of columns and tell the corresponding attributes of each column of DataTables. The title configuration is optional. Adding the title will add a header to the table

From the instance

$(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"}}]); });Copy the code

Ajax asynchronous fetch

Datatables also support asynchronous loading of data using Ajax, which is as simple as configuring a URL

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

The data received by Ajax can be arrays or objects. Note the configuration of columns, which can be used for processing data in the two formats mentioned above

Result data processing

The table above can find that there is a site column content is a website, if we want to make the website can click how to achieve? You can use the Render property of columns to change the display result

$(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"}}]); });Copy the code

The render function is executed whenever the table needs to fetch data from a cell in a column, and may be executed multiple times. By default, the render function takes three arguments, meaning:

Data: The specific data of the cell, for example, https://ops-coffee.cn

Type: identifies the request type of this call, including filter, display, type, and sort

Row: The complete data source for this row. If you pass object data as in the Demo example, you can obtain the row site column data from row.site

After you take the parameters and do a bunch of processing, you can return what you want to show

Of course, you can also add a column at the end of the table through columns to achieve the display of edit and delete buttons

"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": "Operation"."render": function (data, type, row) {
        return '<a href="#update/'+row.id+'/" class=" BTN btn-warning btn-sm"> Edit  ' +
               '<a href="#delete/'+row.id+'/" class=" BTN btn-sm"> delete '}}]Copy the code

The final result is shown below

Dom manipulation

What if I don’t want the datatables to show the number of items per page in the upper left corner, and I want an add button instead? You can do this with the DOM of datatables

By default, tables have per-page displays in the upper left corner, searches in the upper right corner, table information in the lower left corner, pages in the lower right corner, data load waits in the middle, and the table itself. These are the DOM of Datatables, which are essentially a DIV wrapped around SELECT, input, and other HTML tags. Each DOM in a Datatables corresponds to a letter, as follows:

L: length, representing the top left corner of each page display of numerical control pieces

F: Filtering, for the search control in the upper right corner

T: table: indicates the table itself

I: Information, represents the table information control in the lower left corner

P: Pagination, the lower right corner pagination control

R: processing, which indicates the wait prompt control for loading intermediate data

These controls can be configured with the DOM to control where and whether they are displayed in the datatables. The default display order is LFRTIP

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

If you don’t want to display a control, you can do this by removing the corresponding letter from the DOM configuration item, and the Datatables support four custom tags that can easily change the DISPLAY of the DOM

< > Angle brackets represent div in HTML

<“class”> represents the div with the class added

<“#id”> represents the div with the id added

<“#id.class”> represents the div with the id and class added

We want to replace the top right corner of each page display bar with the add button can be written like this

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

You encounter style issues and need to add CSS

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

And that’s perfect

Server-side processing

The server can process data using Datatables. When the server data processing function is enabled, the Server will send Ajax requests to the server when pages are pagination, sorting, and searching. The Ajax requests will send many variables to the server, and the server will process the data according to the values of the variables. After processing, it is returned to the front page in a fixed format, and the page face renders the returned data for users to view

Only two setup items, serverSide and Ajax, are required to enable server mode

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

ServerSide: If the value is true, the server processing mode is enabled

Processing: Indicates that data processing prompts are enabled when the value is true. This parameter is optional

Ajax: Specifies the address of the server. It can be a string like above, or it can be used as an object like jquery. ajax, for example, if I want to pass extra parameters (datatables are passed to the backend server by default, as described below)

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

Data: You can add an additional parameter type= OPs-coffee when sending requests to the back end

Parameters sent to the server

When server data processing is enabled, a number of parameters are passed to the server by default, like the following:

Start: the start position of the first data length: the number of items displayed per page Search [value] : the global search key order[I][column] : Order [I][dir] : tells the server which columns are to be sorted"desc"."asc"Columns [I][data] : searchable [I] : searchable [I] : searchable [I] : searchable [I] : searchable [I] : searchable [I] : searchable [I] : searchable [I] : searchable Columns [I][Orderable] : tells the server which columns can be searched columns[I][search][value] : tells the server the specific search conditions for certain columnsCopy the code

If you need background paging, then you need to get the start and length parameters to do the corresponding processing.

If there is search content, then need to get the serch[value] parameter to process

The format of the data returned by the server

The server needs to return the data format that datatables can handle. The data format is as follows:

{
    "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"} // omit other results]}Copy the code

Draw: identify the number of times the client calls the server. What is passed by the client can be returned as is, without modification

RecordsTotal: Indicates the total number of unfiltered data

RecordsFiltered: indicates the number of filtered entries that meet the requirements. If there are no search parameters, this value is the same as recordsTotal

Data: data to be displayed. The value is in json format

API call

Datatables provides a powerful API for processing data from tables. You can use the API to add data to existing tables or manipulate existing data. The various TYPES of APIS can be found on the official website.

Jump to page

Skip to page 3:

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

table.page(2).draw(false)
Copy the code

Page (2) : Page is a pagination method, followed by a 2 to indicate the page to jump to, can be a number, or a string such as first, next, previous, last, when a number to count from 0, such as the example of 2 is actually jump to page 3

Draw (false) : Redraw the table to display the updated table. Most API operations do not update the page directly, so call Draw. By default, the page will be reset to the first page after redrawing

Search a column

Search for rows in column 2 that contain https://ops-coffee.cn

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

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

Notice first that the API call in this example uses.api(), because the previous example used it during initialization. DataTable() this example is initialized with.datatable (), which is just a case-case-d difference, but it has a different meaning. The former returns an API instance directly, while the latter returns a jQuery instance

Complete Demo

For your convenience, I have written a complete demo, which you can view online or download the code to apply to your own projects

Online Demo address: demo.ops-coffee.cn/datatables/

Github source address: github.com/ops-coffee/…


Related articles recommended reading:

  • Front-end plug-in for Select2 use
  • Bootstrap Dual Listbox for the front-end plug-in