Jquery uses AJAX to obtain information from the background and display the information on the table class, jqueryajax
Some time ago I wrote: jquery uses AJAX to obtain information from the background and display it on the table, and supports row selection. Now, I have processed them and do not need to write code every time:
The Code is as follows:
// Obtain data and display the data table function GetTableData (tableId, ChlickEvent) {var table =$ (tableId); var url = table. data ('url'); $. ajax ({url: url, type: 'post', dataType: 'json ',}). done (function (json) {var fileds = new Array (); table. children ('thead '). children ('tr '). children ('th '). each (function (index, el) {var field = $ (this ). data ('field'); fileds [index] = field ;}); var tbody = ''; $. each (json, function (index, el) {var tr = "<tr>"; $. each (fileds, function (I, el) {if (fileds [I]) {tr + = '<td>' + formatJsonData (json [index] [fileds [I]) + '</td> ';}}); tr + = "</tr>"; tbody + = tr;}); table. children ('tbody '). append (tbody); if (ChlickEvent) {// if You Need To support row selection event table. children ('tbody '). addClass ('sel '); table. children ('tbody. sel '). children ('tr '). click (function (event) {$ (this ). siblings ('tr '). removeClass ('active'); // Delete the selected effect of other rows $ (this ). addClass ('active'); // Add the ChlickEvent ($ (this ). children ('td: eq (0 )'). text (); // Add Click Event });}}). fail (function () {alert ("Err") ;}) ;}// format JSON data, such as date function formatJsonData (jsondata) {if (jsondata = null) {return 'no data';} else if (// Date \ (\ d ++ \)/. exec (jsondata) {var date = new Date (parseInt (jsondata. replace ("/Date (",""). replace (")/", ""), 10); return date. toLocaleString ();} return jsondata ;}
It is very simple to write and has few functions, but it is enough for me to use it. Meet simple requirements.
HTML code must be in the following format. JSON data must be obtained through POST. The obtained address must be written to data-url, and the data column name must be written to data-field.
Click events are supported.
Usage:
<Table id = "RoleGroupTable" class = "table" data-url = "@ Url. action ("GetRoleGroups", "Account ") "> <thead> <tr> <th data-field =" ID "> ID </th> <th data-field =" Name "> Name </th> <th data-field = "Remark"> overview </th> </tr> </thead> <tbody> </table> <script> jQuery (document ). ready (function ($) {GetTableData ('# rolegrouptable', function (id) {alert (id)}) ;}); </script>