[英]How to deal with null values in JQuery DataTable when using ajax
我的页面尝试加载DataTable时出现以下错误:
DataTables警告:表id = table1-请求的未知参数'0'为行0,列0。有关此错误的更多信息,请参见http://datatables.net/tn/4
当我使用随机值的虚拟数据集时,表加载工作正常,但是我要显示的数据具有许多空值,这可能就是问题出现的原因。 我想知道如何最好地设置DataTable设置,以便识别空值并将其显示为空字符串。
我尝试添加一个渲染函数来解决该问题(改编自在datatablesoficial 论坛上的注释中描述的示例),但是它目前无法正常工作,我不确定如何最好地实现它,或者不确定是否会更好完全使用另一种方法。
jQuery的:
function setupData() {
$(document).ready(function () {
$('#table1').dataTable({
"dom": 'B<clear>frtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"scrollX": true,
"scrollY": true,
"ajax": {
"url": "/index_get_data",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
responsive: true
});
});
}
$(window).on("load", setupData);
的HTML:
<table contenteditable='true' id="table1" class="tableBody dataTable table-striped table-bordered nowrap display" style="width:100%" >
<thead>
<tr>
{% for item in cols %}
<th>{{ item }}</th>
{% endfor %}
</tr>
</thead>
</table>
我添加到dataTable声明中的渲染函数,但无法正常工作:
"render": function jsRenderCOL(data, type, row, meta) {
var dataRender;
if (data == null) {
dataRender = "";
}
return dataRender;
}
有超过130列(这可以是可变的),并且数据每天都会更新,许多列可能包含空数据。 我想找到一种方法来显示dataTable中的数据,而不必在dataTable函数中显式声明列。 感谢您的任何帮助,您可以提供。
您不必担心ajax数据使用此代码
$('.dataTable').dataTable({ destroy: true, paging: true, searching: true, sort: true, "ajax": { url: '{{ url('users/datatable')}}', type: 'POST', headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' }, 'data':{} }, "columns": [ {data: 'id'}, {data: 'name'}, {data: 'email'}, {data: 'membership_no'}, {data: 'is_active'}, {data: 'varsity_session'}, {data: 'due_amount'}, {data: 'paid_amount'}, {data: 'created_at'}, {data: 'last_transaction_date'}, {data: 'action'}, ], "columnDefs": [ {"bSortable": false, "targets": [1, 6]}, {"searchable": false, "targets": [4, 6]} ], lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]], pageLength: 10, "dom": 'Blfrtip', buttons: [ { extend: 'copy', text: 'copy', className: 'btn btn-primary', exportOptions: { columns: 'th:not(:last-child)' } }, { extend: 'csv', text: 'csv', className: 'btn btn-warning', exportOptions: { columns: 'th:not(:last-child)' } }, { extend: 'excel', text: 'excel', className: 'btn btn-danger', exportOptions: { columns: 'th:not(:last-child)' } }, { extend: 'pdf', text: 'pdf', className: 'btn btn-success', exportOptions: { columns: 'th:not(:last-child)' } }, { extend: 'print', text: 'print', className: 'btn btn-btn-info', exportOptions: { columns: 'th:not(:last-child)' } } ] }); });
您可以尝试在初始化时将每一列的defaultContent设置为空字符串,即
$('#table1').dataTable( {
"columnDefs": [ {
"targets": (pass a variable in here that you have calculated based on the number of columns to render)
"defaultContent": ""
} ]
} );
对于targets属性,请传入定义列索引的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.