<script> //I usually put the script section at the end of head tag
var table_1; //declare your table var here and initialize as a datatable inside document ready below.
$(document).ready(function() {
table_1 = $('#table_1').DataTable( {
dom: "Bfrtip",
ajax: {
url: "/get-data", //path where json data will be served from. ex: get-data.php or my-data.json
type: "POST" //use POST to not have to deal with url encoding various characters
},
serverSide: true,
searchDelay: 2000, // use this to throttle ajax requests when typing in search input
processing: true, // optional visual indicator that a search has been sent to backend
lengthMenu: [ 10, 25, 50, 75, 100 ], // define per page limits. first value will be the default
buttons: [
"pageLength" // per page drop down button. i usually override/extend the default button
],
columns: [ // column definitions of json data fields
{ data: "status_id", title: "ID", width: "1%" }, // width:1% makes col width as small as possible
{ data: "status", title: "Status(hidden)", visible:false }, //visible:false hides column but allows you access to field data
{ data: "reason", title: "Reason and Status", render: function ( data, type, row ) { //render allows combining of fields into single column
return data + ' <small>('+row.status+')</small>'; // data will be reason value. row.status is how you reference status value
} },
{ data: "current", title: "Current", searchable:false }, //searchable: false set this field to not be used in search
{ data: null, title: "Button", render: function ( data, type, row ) { // use data:null if you need to render stuff in a column that does not necessarily need to be tied to a specific data value
if(row.current){
return '<button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="'+ row.status_id +'" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button>';
}
else{
return '<button>Different Button</button>';
}
} },
],
rowId: 'status_id' //sets the tr row id to the value in this column. useful for DOM and other manipulation later
} );
}
</script>
<table id="table_1" class="table table-striped table-bordered table-sm" style="width:100%"></table>
<!-- If you define the title attributes in json column definitions above
then you don't need to create html table headers/footers.
Just an empty table tag will do. -->
Ваш URL-адрес ajax должен будет возвращать данные в формате JSON с массивом объектов:
[
{
"author": "KK2342",
"up_to": "09/30/2017",
"status": "Approved",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Close",
"status_id": "479664"
},
{
"author": "DD7822",
"up_to": "09/30/2017",
"status": "Close",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Process",
"status_id": "479666"
}
]
Для начала создайте файл с именем testing.json свыше содержание. Затем замените table_1 ajax-url из приведенного выше примера на /your_folder_path/testing.json. Этот набор данных должен теперь загружаться.
Чтобы получить доступ к данным, все, что вам нужно сделать, это позвонить:
table_1.data(); // datatables object
//OR
table_1.data().toArray(); // a simple array of objects with each rows data you can loop through
Документы по манипулированию данными для каждой строки можно найти здесь: https://datatables.net/reference/api/row().data()
После изменения данных вы можете использовать table_1.draw () или table_1.reload (), как предложено @NawedKahn, - в зависимости от вашего варианта использования.
Тонны полезногофункциональные возможности можно найти в Документах ниже
Все, что вы можете делать с объектами данных: https://datatables.net/reference/api/
Все параметры данных: https://datatables.net/reference/option/
Просмотрите эти ссылки, прежде чем пытаться создать какую-либо функциональность, возможно, она уже существует.