我在识别代码中的问题时遇到了麻烦。
我正在做一个搜索脚本,我想在数据表中显示结果。我有一个搜索表单,它将数据发送到我的 php 文件并返回查询结果的json_encode,然后在 ajax 成功时,我构建我的表,将结果传递到"data":响应中。
当我在没有数据表的情况下进行查询时,查询工作得很好,但由于我需要分页和其他东西,我需要它在数据表上工作。
表格的 HTML :
<div id="results">
<table id="example" class="display compact hover stripe" cellspacing="0" width="100%">
<thead>
<th>Cognome</th>
<th>Nome</th>
<th>Telefono</th>
<th>Provincia</th>
<th>Tipo Cliente</th>
<th>Amministrazione</th>
<th>Stato</th>
<th>Fonte</th>
<th>Data Ricezione</th>
<th></th>
</thead>
</table>
</div>
Javascript for Datatable:
$('#submit_src').on("click", function() {
$.ajax({
data: $("#ricerca").serialize(),
type: $("#ricerca").attr('method'),
url: $("#ricerca").attr('action'),
success: function(response) {
$('#example').dataTable( {
"data": response,
"sPaginationType": "listbox",
"bFilter": false,
"jQueryUI": true,
"processing": true,
'iDisplayLength': 25,
} );
}
});
return false;
});
"submit_src"当然是我的提交按钮,"Ricerca"是我的表单名称。
我得到的 json 代码是:
{"sEcho":0,"iTotalRecords":"35036","iTotalDisplayRecords":"1","aaData":[["stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff"]]}
错误:
DataTables warning: table id=example - Requested unknown parameter '1' for row 0.
此链接可能有助于您尝试完成的任务:http://datatables.net/release-datatables/examples/ajax/objects.html。它解释了数据表需要数据的数组;但是,为了使用这些对象,可以使用 columns.data 选项来完成。
我也在没有<tbody>
的情况下使用了数据表,所以这应该不是问题。
编辑:尝试以下操作,我能够将"东西"显示在表格中:
$('#example').dataTable( {
"data": response.aaData
} );
编辑 2:
jQuery(document).ready(function() {
var response = {
"sEcho":0,"iTotalRecords":"35036","iTotalDisplayRecords":"1",
"aaData": [
["stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff"]]
};
$('#example').dataTable( {
"data": response.aaData,
//"sPaginationType": "listbox",
"bFilter": false,
"jQueryUI": true,
"processing": true,
'iDisplayLength': 25
} );
});
您可能缺少该选项
dataType : "json",
在你的代码上。如果未指定,这可能会混淆从 ajax 脚本接收的数据类型。
我相信DataTables需要<tbody></tbody>
,以便它知道将返回的数据放在哪里。尝试将其添加到您的table#example
中。
<table id="example" class="display compact hover stripe" cellspacing="0" width="100%">
<thead>
<th>Cognome</th>
<th>Nome</th>
<th>Telefono</th>
<th>Provincia</th>
<th>Tipo Cliente</th>
<th>Amministrazione</th>
<th>Stato</th>
<th>Fonte</th>
<th>Data Ricezione</th>
<th></th>
</thead>
<tbody></tbody>
</table>