The DataTables ajax option, documented here, is a common way lớn retrieve dynamic data from a source, for loading into a table.
Bạn đang xem: Dynamically populate jquery datatable with json data on ajax request
Typically, I use this option with an object - something lượt thích this:
1234567 | $('#example').dataTable( "ajax": "url": "https://myurl.goeshere.com/mydata", "type": "POST", "dataSrc": "my_data" ); |
This is basically a wrapper around the jQuery ajax() API - with the addition of dataSrc khổng lồ help DataTables locate its row iteration starting point.
However, you can also use a function with the DataTables ajax option, instead of an object. The following fragment shows an example:
1 2 3 4 5 6 7 8 91011121314151617181920212223242526 | $(document).ready(function() var table = $('#demo').DataTable( ajax: function (data, callback, settings) $.ajax( url: "http://localhost:7000/ajax-employee-objects", ).then ( function( json, textStatus, jqXHR ) json<"data"> = json<"row_objects">;delete json<"row_objects">;//console.log(textStatus); // "success"https://console.log(json.extra_data.foo); // "bar" callback(json); ); , columns: < data: "name" , data: "position" , data: "office" , data: "extn" , data: "start_date" , data: "salary" > ); ); |
This approach allows you to lớn process the JSON response from the ajax call, before passing the row array data khổng lồ DataTables. You can therefore re-arrange the JSON data, and process additional data in the JSON if needed.
In this specific example, the option uses a function. In this case, it’s up khổng lồ you to lớn make the actual ajax điện thoại tư vấn (e.g. Using jQuery’s ajax API, as shown above).
Xem thêm: Bí Quyết Cắm Hoa Đồng Tiền Giữ Cho Hoa Tươi Lâu Nhất, Bí Quyết Chọn Bó Hoa Đồng Tiền Đẹp
The three parameters made available in this option are:
data | The data to lớn be sent to the server. |
callback | Callback function that must be executed when the required data has been obtained from the ajax request. That data should be passed into the callback as the only parameter. |
settings | The DataTable settings object. |
In our example the callback function re-names the data array from row_objects to data:
This is needed because DataTables expects the data array to lớn be called data - và the normal approach (using dataSrc: "row_objects") is not available when the ajax function is used.
An example of the JSON handled by the above code is:
|