Jquery datatables - get columns from json

In jquery datatables can I define server side columns of a script? I need something like this enter image description here

Date columns must be loaded from the server. Then the number of columns may vary.

+5
source share
2 answers

To expand on what Kamal Deep Singh talked about:

You can dynamically create a table on the fly, and then apply data to it to get the functionality of the data.

// up in the html
<table id="myDatatable" class="... whatever you need..."></table>

and then:

// in the javascript, where you would ordinarily initialize the datatable
var newTable = '<thead><tr>'; // start building a new table contents

// then call the data using .ajax()
$.ajax( {
    url: "http://my.data.source.com",
    data: {}, // data, if any, to send to server
    success: function(data) {
        // below use the first row to grab all the column names and set them in <th>s
        $.each(data[0], function(key, value) {
            newTable += "<th>" + key + "</th>";
        });
        newTable += "</tr></thead><tbody>";                  

        // then load the data into the table
        $.each(data, function(key, row) {
             newTable += "<tr>";
              $.each(row, function(key, fieldValue) {
                   newTable += "<td>" + fieldValue + "</td>";
              });
             newTable += "</tr>";
        });
       newTable += '<tbody>';

       $('#myDatatable').html(newTable); // replace the guts of the datatable table placeholder with the stuff we just created. 
    }
 });

 // Now that our table has been created, Datatables-ize it
 $('#myDatatable').dataTable(); 

Please note that you can put parameters into this .dataTable () as usual, but not 'sAjaxSource' or any of the functions for receiving data associated with it - this is applying data to an existing table that we created on the fly.

, , .

. . : https://github.com/DataTables/DataTables/issues/273

+5

, ,

+ Q ', ...

$.ajax( {
    "url": 'whatever.php',
    "success": function ( json ) {
        json.bDestroy = true;
        $('#example').dataTable( json );
     },
    "dataType": "json"
} );

json - -

{

"aaData": [
[ "2010-07-27 10:43:08", "..."], [ "2010-06-28 17:54:33", "..."],
[ "2010-06-28 16:09:06", "..."], [ "2010-06-09 19:15:00", "..."]
] ,

 "aaSorting": [
  [ 1, "desc" ]
 ],

 "aoColumns": [
   { "sTitle": "Title1" },
   { "sTitle": "Title2" }
 ]

}

JSON (ajax)

+5

All Articles