在使用ajax源数据时,如何使用DataTables的initComplete回调在ajax重载后更新数据



我正在使用一个select对象来触发DataTable的ajax重载。我需要为给定的列添加单独的列搜索和select输入(不是为每一列(,但select中填充了以前的ajax响应。如何更新initCompleteFunction回调用于填充单个列搜索中的选择输入的数据?

// this is the select that triggers the ajax.reload
$('#proveedor').on('change', function () {
$datatable
.DataTable()
.ajax
.reload(initCompleteFunction, false);
});
// this is my initCompleteFunction callback
function initCompleteFunction(settings, json){
var api = new $.fn.dataTable.Api( settings );
api.columns().every( function () {
var column = this;
if ($(column.header()).hasClass('select')) {
var select = $('<select><option value="">' + $(column.header()).html() + '</option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);  
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
return false;
} );
//this is the part that keeps previous data insted of the new one from the ajax reload
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
}
});
}

// and this is how I’m setting the DataTable
var $datatable = $('#table_materiales');
$datatable
.on('xhr.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);        
})
.DataTable({
"ajax": {
"url": "http://my_endpoint",
"dataSrc": "",
"type": "POST",
"data": {
id_proveedor: function () {
return $('#proveedor').val(); // to get the value in the provider’s filter (select)
}
}
},
"columns": [
{
data: 'row_num'
},{
className: "select",
data: 'material'
},        
// here goes the rest of the column definitions
],
"paging": false,
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [
[3, 'asc']
],
"createdRow": function (row, data, dataIndex) {
$(row).attr('data-id-material', data.id_material); 
$(row).attr('data-pedido_sugerido', data.pedido_sugerido);
$(row).attr('id', 'id_' + data.row_num); 

if(data['status_de_tiempo']=='FUERA'){
$(row).addClass('redClass');
}
},
});

在研究过程中,我发现xhr.dt事件是在ajax.reload((完成之前触发的,因此当填充单个列搜索的选择时,数据会过时。参见本参考

用户grozni在2019年4月发布了这篇文章:

我使用了控制台日志,并且能够确认事件在XHR事件结束之前触发,并且不会提取最新的JSON。我在可能的地方使用了XHR跟踪,但这仍然很不方便,也让事情变得复杂。我需要能够在数据加载和绘制后做某些事情。也许它值得一个错误报告

我发现了这篇文章(请参阅此处(,用户conangithub需要

在成功重新加载DataTable 后计数DataTables项目

用户lovecoding git建议使用这种方法:

table= $('#example').DataTable();
$('#example').on('draw.dt', function() {
console.log(table.ajax.json().recordsTotal);
});

所以,对于我自己的问题,而不是

.on('xhr.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);        
})

我写了

.on('draw.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);        
})

等等。

我得到了所需的解决方案。

最新更新