I use DataTable. I send data to datatable onclick in json file. The problem is When I use $('.datatable-ajax-source table').dataTable().fnDestroy();
I loose the filter, row and pagination. I get just the table like below:
This my fuction javascript:
$('#ButtonPostJson').on('click', function() {
var forsearch = $("#searchItem").val();
$.ajax({
processing: true,
serverSide: true,
type: 'post',
url: 'path.json',
dataType: "json",
success: function(data) {
$.each(data, function(i, data) {
var body = "<tr>";
body += "<td>" + data.name + "</td>";
body += "</tr>";
$('.datatable-ajax-source table').append(body);
});
/*DataTables instantiation.*/
$('.datatable-ajax-source table').dataTable().fnDestroy();
},
error: function() {
alert('Fail!');
}
});
});
And when I replace $('.datatable-ajax-source table').dataTable().fnDestroy();
with $('.datatable-ajax-source table').dataTable();
I get this table who I want
But when I want to search for a new term the old data is still there,I have to refrech the page manually for doing a new search. How can I refresh or update my datatable?
I'm using fnStandingRedraw to refresh the server side data and it works like a charm (unfortunately its deprecated though). You can use https://datatables.net/plug-ins/api/fnStandingRedraw
var ajaxSourceDataTable;
//define datatable
ajaxSourceDataTable = $('.datatable-ajax-source table').dataTable()
//use this code to redraw/refresh datatable
ajaxSourceDataTable.fnStandingRedraw();
You're missing the best parts of dataTables using it in this manner. Don't build your HTML manually.... use the .rows.add() (and related) functions to redraw your table as needed.
Try this:
https://jsfiddle.net/xgpgLydb/
var tbl = $('#example').DataTable({
columns: [{
data: 'Prop1',
title: 'Example Prop'
},{
data: 'Prop2',
title: 'Example Prop 2'
}]
});
var req = $.ajax({
url: '/echo/json/',
method: 'post',
data: {
json: JSON.stringify([{
Prop1: 'Foo',
Prop2: 'Bar'
},{
Prop1: 'Fred',
Prop2: 'Flinstone'
}]),
delay: 1
}
});
req.done(function(response) {
tbl.rows().remove().draw();
tbl.rows.add(response).draw();
});
这个链接在jQuery DataTables中刷新数据确实很有帮助,我从中得到启发来解决我的问题。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.