jquery - DataTables jQuery插件在初始加载后设置recordsTotal

标签 jquery performance datatables

我已经在互联网上搜索过这个问题,但似乎找不到答案......

我有一个相对复杂的查询,它从大型数据库中返回 50 条记录。此查询作为游标运行,因此速度很快,并且能够在大约 20 毫秒内组装 json 并返回数据表。

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

我希望能够执行并行 ajax 调用,并在数据表渲染后设置计数 (recordsCount),以便我可以更快地在屏幕上看到数据。这可能吗?

作为一种解决方法,我正在考虑为我的查询创建计数缓存,但如果我能够在能够获取计数时轻松命中某些客户端代码,这似乎并不理想。

这是我的数据表代码供引用:

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){

    }
  })

最佳答案

这是一个有趣的问题。

我可以为您提供一种巧妙的方法。它应该适用于 DataTables 1.10.x。

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

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

然后使用一些内部未记录的函数更新数据表。

$('#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用于代码和演示。

关于jquery - DataTables jQuery插件在初始加载后设置recordsTotal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449644/

相关文章:

javascript - scrollTop() !== 不起作用

jquery - 动态生成的 html 上的 z-index 元素

apache-flex - 为什么 Flex 使用单线程模型?

python - 检查两个二维 numpy 数组的公共(public)元素,无论是行还是列

javascript - 为 DataTables.js 元素提供特定的 id/class/names

javascript - DataTable() 没有给出正确的对象引用

javascript - html 中的猫头鹰轮播不会自动移动

javascript - highcharts - 热图底部不需要的空间

java - 嵌套循环运行时间复杂度分析

angularjs - 在 AngularJS 中使用数据表按钮扩展