如何制作数据表来处理 Ajax 请求?

How to make datatables to handle Ajax requests?

我希望数据表自行处理 Ajax 调用来填充它,所以我有这个配置:

$('#tabela-usuario-portal').dataTable({
"responsive": true,
"ordering": false,
"retrieve": true,
"ajax": 'usuario/pesquisaUsuario',
"lengthMenu": [5, 10, 20],
"columns": [
    { "data": "usuario" },
    { "data": "email" },
    { "data": "cpf" }
],
"language": {
    "lengthMenu": "Exibindo _MENU_ por página",
    "zeroRecords": 'Nada',
    "paginate": {
        "previous": "Anterior",
        "next": "Próximo"
    }
},
"dom": 't<"tfooter"pl>'
});

和这个 HTML:

<table id='tabela-usuario-portal' class="tabelaGrid table-hover">
    <thead>
        <tr>
            <th>usuario</th>
            <th>email</th>
            <th>cpf</th>
        </tr>
    </thead>
</table>

Datables 成功发出 ajax 请求,并返回以下内容:

[{"id":22,"id_sgp":24539,"cpf":"58287467748","email":"ffa@aa.com","usuario":"terminator","cod_perfil"
:1,"situacao":"A"},{"id":30,"id_sgp":33951,"cpf":"24423229196","email":"zeze@indra.es","usuario":"tetris"
,"cod_perfil":89,"situacao":"A"},{"id":28,"id_sgp":34001,"cpf":"31155957865","email":"af@j.com","usuario"
:"zczc","cod_perfil":89,"situacao":"A"}]

但我收到一个错误:

TypeError: f is undefined

我想我快到了,我只需要在 JSON 的数据和他各自的位置之间做出正确的引用。我已经阅读了文档,但无法弄清楚。任何帮助将不胜感激。

SOLUTION

添加 ajax.dataSrc 并将其设置为空字符串 ('') 以匹配您的数据结构,如下所示:

var table = $('#tabela-usuario-portal').DataTable({
    ajax: {
        url: 'usuario/pesquisaUsuario',
        dataSrc: '' 
    },
    /* ... skipped ... */
});

来自ajax.dataSrc选项说明:

Note that if your Ajax source simply returns an array of data to display, rather than an object, set this parameter to be an empty string.

DEMO

有关代码和演示,请参阅 this jsFiddle