我是Web开发的新手。我尝试在ajax成功之后将数据设置为datatable
。在成功方法中,如果有可用数据,它将正确显示,但在没有数据成功的情况下,将刷新以前的数据。
$("button#search").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var url = "/searchCustomer/searchCust";
$.ajax({
type : "POST",
url : url,
data : {name:name,age:age},
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(data) {
var table = $('#customerTable').DataTable( {
data : data.data,
columns: [
{"data": "customerid" },
{"data": "name"},
{"data": "mobilenumber"},
{"data": "status"}
],
"language": {
"lengthMenu": "View _MENU_ records per page",
"zeroRecords": "No matching records found",
"infoEmpty": "No records available",
"infoFiltered": "(filtered from _MAX_ total records)"
},
"pagingType": "full_numbers"
})
},
error : function(e) {
alert("error");
}
});
第一次单击按钮时,如果可用数据显示正确,则第二次单击按钮,但在这种情况下没有数据刷新旧数据。
JSON数据格式:
1。{"data":[{"customerid":"xxxxxxxxxx","name":"Sourabh Yadav","mobilenumber":"XXXXXXXXXXX","status":"In-Active"}]}
2。{"data":null}
答案 0 :(得分:0)
如果没有数据,则可以使用fnClearTable()
清除数据表。在成功使用ajax时使用它:
var dataTable = $('#customerTable').dataTable();
if (data.data == null) {
dataTable.fnClearTable();
} else {
// set your datatable here
}
答案 1 :(得分:0)
只需在每次ajax调用$('#customerTable').empty()
答案 2 :(得分:0)
尝试此代码,因为您必须已经加载表实例,然后清空数据,然后重新初始化
$("button#search").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var url = "/searchCustomer/searchCust";
$.ajax({
type : "POST",
url : url,
data : {name:name,age:age},
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(data) {
if ( $.fn.DataTable.isDataTable('#customerTable') ) {
$('#customerTable').DataTable().destroy();
}
$('#customerTable').empty();
var table = $('#customerTable').DataTable( {
data : data.data,
columns: [
{"data": "customerid" },
{"data": "name"},
{"data": "mobilenumber"},
{"data": "status"}
],
"language": {
"lengthMenu": "View _MENU_ records per page",
"zeroRecords": "No matching records found",
"infoEmpty": "No records available",
"infoFiltered": "(filtered from _MAX_ total records)"
},
"pagingType": "full_numbers"
})
},
error : function(e) {
alert("error");
}
});