2017-08-02 71 views
1

我已经冲刷互联网,因此,对于这个,但似乎无法找到答案...数据表jQuery插件初始加载后设置recordsTotal

我有一个从大返回50条记录一项相对复杂的查询数据库。该查询作为游标运行,因此速度很快,能够组装json并在〜20ms内返回到数据表。

但是,获取此查询记录的总计数较慢(500毫秒)。

我希望能够做一个并行的Ajax调用,并设置我的数据表上的计数(recordsCount)后,它已经呈现,所以我可以更快地看到屏幕上的数据。这可能吗?

作为一种解决方法,我正在考虑为我的查询创建一个计数缓存,但如果我能够轻松地打到某些客户端代码时,这看起来并不理想。

这里是我的DataTable参考代码:

var table = $('#myTable').DataTable({ 
    "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>', 
    "processing": true, 
    "serverSide": true, 
    "searching": false, 
    "ordering": false, 
    "bSort": false, 
    "scrollX": false, 
    "fixedHeader": true, 
    "deferRender": true, 
    "iDisplayStart": (startPage * pageLength), 
    "ajax": { 
     "url": url, 
     "type": "POST", 
     "data": function (d) { 

     } 
    }, 
    "pagingType": "full_numbers", 
    "columnDefs": columnDefs, 
    "responsive": false, 
    "columns": columnDataStructure, 
    "order": [[0, "desc"]], 
    "lengthMenu": [10,25,50,100], 
    "initComplete": function(settings, json){ 

    } 
    }) 

回答

0

这是一个有趣的问题。

我可以为您提供一个hacky的方式来做到这一点。它应该适用于DataTables 1.10.x.

附加以下事件处理程序,当DataTables向服务器端脚本发出Ajax请求时将调用该事件处理程序。

调用另一个服务器端方法(在我的示例中为/echo/json/)并检索总记录数。

然后使用某些内部未记录的函数更新DataTables。

$('#example').on('xhr.dt', function (e, settings, json, xhr) { 
    $.ajax({ 
     url: '/echo/json/', 
     method: 'POST', 
     data: { json: JSON.stringify({ recordsTotal: 999 }) }, 
     type: 'json' 
    }) 
    .done(function(json){ 
     settings._iRecordsDisplay = json.recordsTotal; 
     settings._iRecordsTotal = json.recordsTotal;  
     $.fn.dataTable.ext.internal._fnCallbackFire(settings, 'aoDrawCallback', 'draw', [settings]); 
    }); 
}); 

请参阅this example的代码和演示。

+0

哇。这工作!非常感谢Gyrocode.com! – Rao

+0

@Rao,别忘了在原始响应中为'recordsTotal'和'recordsFiltered'返回一些虚拟数字。 –