JQuery DataTable Spreadsheet Plug-in table basic initialization

Source: Internet
Author: User
Tags tomcat server
jQuery DataTable The plug-in table is basically initialized

This article introduces the basic use of the table initialization of jquery DataTable, the DataTable is the front-end table interface plug-in with high usage, so it is easy to create responsive table, it can easily realize the function of page paging, filtering and sorting.

JQuery DataTable Table Basic initialization Introduction file HTML code JS code hint Information header initialization DataTable table initialization considerations and problems encountered in the summary

Introducing Files

<script type= "Text/javascript" src=./plugin/jquery/jquery-1.11.2.js "></script>
<script type=" Text/javascript "src="./script/jquery.datatables-1.10.12.min.js "></script>
<script type=" text/ JavaScript "src=" Datatablecontroller.js ></script>

The script files listed above are jquery script files, DataTable script files, and our own coded DataTable initialization script.

<link href= "./plugin/bootstrap/css/bootstrap.min.css" rel= "stylesheet"/> <link "
. href= Jquery.dataTables.min.css "rel=" stylesheet "/>
<link href="./css/datatables.bootstrap.min.css "Rel=" Stylesheet "/>

For the introduction of the style file, the first one for the bootstrap frame style, where the second and third can be two selected, respectively, based on jquery and Bootstrap DataTable style.

Note: using the jquery-based DataTable style, you need to create a folder images in the project root, where you put the resource picture in the DataTable plug-in (main display sort icon)

Where the jquery style is roughly:

Bootstrap style:
HTML Encoding

Because the encoding described in this article is to initialize a table in a script, the table's parameters and data are defined in the script, and only one div tag in the HTML is used to locate it.

<div class= "col-md-10 col-md-offset-1" id= "Testtable_div" ></div>

Where Col-md-10 col-md-offset-1 represents the bootstrap layout, uses a medium screen for page 10 columns (12 columns in total), and offset represents the left margin offset by one column. JS Code

The initialization code for the table is in the JS script. Hint Information

-First, define the table's hint information , you can do internationalization, in order to look convenient here directly assigned value:

var language = {
        "processing": "<span>&nbsp;&nbsp; '" + "Processing ..." + "</span>",
        "Lengthmenu": "_menu_ results per page",
        "zerorecords": "No match result",
        "info": "<span class= ' seperator ' >  </span> ' + ' found a total of _total_ results ',
        ' infofiltered ': ' (obtained from All _max_ Records) ', '
        Infoempty ": Total 0 items",
        "emptytable": "The data in the table is empty",
        "Paginate": {
            "previous": "Front page",
            "Next": "Next Page",
            " First ":" Page One  ",
            " last ":"  End "
        }
    };

Code resolution: Processing for the waiting information displayed during the initialization of the table, where the dynamic diagram of the load circle is introduced and the text "process is set ..." lengthmenu how many results are displayed per page for the selectable table, "_menu_" corresponding to the selection of the Drop-down menu zerorecords for the table search filter results are empty hints, emptytable for table empty prompts, are displayed in the table info, infofiltered, infoempty are displayed outside the table, for tabular data information paginate For table paging options, Previous, Next, first, and last are initialized with different navigation label headers

Then, the header is initialized, where the fields and parameters of the header correspond to the data and properties of the table:

var column=[{"Data": "id", Name: "id", "orderable": true}, {"Data": "Name" , Name: "Name", "Orderable": false}, {"Data": "Gender", Name: "Gender", "orderable": false}, {"Dat

A ': ' Age ', Name: ' Age ', ' orderable ': false},];
var divid= ' Testtable_div ';

var tableid= ' testtable '; var tableelestr = ' <table class= ' table table-striped table-bordered table-hover ' id= ' +tableid+ ' > ' + ' <the Ad> ' + ' <tr role= "row" class= "heading" > ' + ' </tr> ' + ' </thead> ' + '

    ;tbody> ' + ' </tbody> ' + ' </table> ';

    $ (' # ' + divid). Append (TABLEELESTR);
    var Trele = $ (' # ' + tableId + ' > Thead >tr ');
        For (var one in column) {var th = ' <th> ' + column[one].name + ' </th> ';
    trele.append (TH); }

Code Resolution: in column, data is the field for each column in the header, name for the header, and orderable indicates whether the column can be sorted to the DIV tag $ (' # ' + divID) that is positioned in the HTML using the selector. To add a table child element and initialize it based on the column initialization table header DataTable table

The following is a call to the jquery plugin DataTable , initializing the table:

    var table = $ ("#" + tableId). DataTable ({"Dom": "<" top "frt><" bottom "lip>", "language": Language,//language "Pagin" Ate ": true,//page button" Searching ": true,//Search bar" Autowidth ": True,//automatically set the C  Olumn width "Lengthchange": true,//record number in per row "Displaylength": 5,//row number in each Page "Lengthmenu": [[5,10,20,-1],[5,10,20, "All"], "ordering": true,//Sort "info": true,//Sh Owing info "scrolly": "Scrollcollapse": True, "Pagingtype": "Full",//page style P Rocessing ": True," ServerSide ": false," destroy ": true," Ajaxsource ":" Json.txt "," columns
            ": Column," Columndefs ": [{defaultcontent: ', Targets: [' _all ']           }],/* "Fnserverdata": Function (ssource, Aodata, Fncallback, osettings) {         
               OSETTINGS.JQXHR = $.ajax ({"type": ' Get ', ' url ': ssource,                                       
                    "DataType": "JSON", "Success": function (RESP) {

                    Osettings.idraw = Osettings.idraw + 1; Resp = Resp.data | |
                    [];
                    var data = {};
                    Data.aadata = resp;

                    var totalcounts = resp.length;
                    Data.itotalrecords = totalcounts;
                    Data.itotaldisplayrecords = totalcounts;
                    Data.secho = osettings;
                Fncallback (data);
                    }, "Error": function (RESP) {var data = {};
                    Data.aadata = [];

                    var totalcounts = 0;
                    Data.itotalrecords = totalcounts;
                    Data.itotaldisplayrecords = totalcounts;
  Data.secho = osettings;                  Fncallback (data);

        }
            }); }*/
    });

Code Resolution: $ ("#" + tableId). DataTable (); For the DataTable initialization function, the selector navigates to the table call DataTable () function to set the display of the table control by setting a different parameter (using the default value without setting) the DOM parameter.
L-length changing input control
f-filtering input
T-the table
I-table Information Summary
P-pagination Control
R-processing display Element
Here ' < ' top "frt><" bottom "lip>" indicates that the above table displays the processing hint control and the search filter control, the table below displays the page-flipping, the data result information and selects the display data the numerical control piece language That is, use the previously defined language variable to assign values Paginate, searching, autowidth, Lengthchange, ordering, info, processing, respectively, to set a Boolean representation of whether the page is implemented, filtered, Automatic response column width, number of display data per page Select, sort, prompt, and process wait control "Displaylength": 5 shows the number of data per page
"Lengthmenu": [[5,10,20,-1],[5,10,20, "all"]] means the entry selected by the Drop-down control, "All" corresponds to-1 that shows all "scrolly": 300,
' Scrollcollapse ': True, two parameters are used in conjunction with the fixed height of a given table, adding the scroll bar "Pagingtype" when the display data exceeds that height: "Full" indicates the format of the paging control, and the other format is numbers, simple, Simple_numbers, Full_numbers

"ServerSide": false, which means that functions such as filtering are not processed on the server, and are handled on the client side (when the amount of data in the table is particularly large, setting to true is appropriate for server-side processing)
' Destroy ': True to indicate that the selector corresponds to an existing table when the table is initialized

"Ajaxsource": "Json.txt", an AJAX data source for reading tabular data, here is a text file
' Columns ': column, set to previously defined column variable
"Columndefs": [
{

        Defaultcontent: ",
        targets: [' _all ']
    }
],

Columndefs is used to set the specific properties of a column, which means that when the incoming data is null or undefined, the cell defaults to empty (avoid prompting for error warnings) and target is all columns

The above has achieved the initialization of the table, the annotation fnserverdata for the server to obtain data processing functions, do not customize the case has the default implementation, here mainly in the error when the table empty instead of prompting error considerations and problems encountered

The above description of the use of the DataTable, especially the meaning of the parameters can be found in:
the problems that Https://datatables.net/reference/index encountered

Also encountered some problems that are not easy to find, give their own solutions:


-To get the text file in "Ajaxsource": "Json.txt" and to open the Web page directly in the browser, a xmlhttprequesterror appears, resolving to put both the project and the text file into the Tomcat server and start the service. Get data from the server or start a service yourself
- JSON format problem : Ajaxsource will parse JSON-formatted text into JSON objects, text to be in JSON format Json.txt
{" Data ': [{' id ': ' 1 ', ' name ': ' A ', ' gender ': ' Male ', ' age ': '},{' id ': ' 2 ', ' name ': ' B ', ' gender ': ' Male ', ' age ': '},{', ' age ' : "3", "Name": "C", "gender": "Male", "Age": "},{" id ":" 4 "," Name ":" D "," gender ":" Male "," Age ":"},{"" id ":" 5 "," Name ": "E", "gender": "Male", "Age": "},{" IDs ":" 6 "," Name ":" F "," gender ":" Male "," Age ":"},{"" id ":" 7 "," Name ":" G "," gender " : "Male", "Age": "},{" id ":" 8 "," Name ":" H "," gender ":" Male "," Age ":"},{"" id ":" 9 "," Name ":" I "," gender ":" Male "," the Age ":"},{"id": "Ten", "Name": "J", "gender": "Male", "Age": "},{" ID: "One", "name": "K", "gender": "Male", "Age": "25"}]} And the JSON field needs to correspond to the column "Data" field defined by the Columns option (that is, the header) in order to properly populate the table and prompt for errors when JSON cannot match, setting Columndefs to resolve summary

In the use of the DataTable process found that the DataTable implementation is relatively simple and easy to expand, but also encountered many problems lookup API can not be resolved, there are 1.10 versions of many parameters and methods are very different easily confused. This article briefly introduces the basic initialization of the DataTable table, and then introduces a more practical advanced example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.