如何使用 Datable Jquery 动态加载数据?

How to Load data dynamically onscroll with Datable Jquery?

我正在尝试使用带有 jquery 的 DATATABLE 插件在没有分页的情况下动态加载数据。 我的数据库中有 3000 多行,加载需要很长时间,所以我想在用户滚动到最后的 table 时加载 200 行这些数据。

这是我的 javascript 代码

 <script src="{{asset('backend/js/demo/datatables-demo.js')}}"></script>
  <script>
      
      $('#user-dataTable').DataTable( {
        
          "bInfo": false, //Dont display info e.g. "Showing 1 to 4 of 4 entries"
          "paging": false,//Dont want paging                
          "bPaginate": false,//Dont want paging
            
        } );

  </script>

想你!

您需要在滚动事件中获取新记录

$(function() {

  var $mytable = $("#myTable");
  var page = 10;
  var count = 10; //initial number of rows 
  var max = 500; //max number of rows (just for demo)
  var $datatable = $mytable.DataTable({
    "paging": false,
    "bFilter": false
  }); //init the datatable and return a refence to it



  //listen for scroll and resize and custom 'fetchmore' events
  $(window).bind('scroll resize fetchmore', function() {
    var viewportHeight = window.innerHeight;
    var scrolltop = $(window).scrollTop();
    var bottomOfTable = $mytable.offset().top + $mytable.outerHeight();

    //console.log(viewportHeight, scrolltop, bottomOfTable);

    if ($(window).scrollTop() + viewportHeight >= bottomOfTable) {
      if (count < max) {
        //console.log("Fetch more data!");
        load_more();
        $(window).trigger("fetchmore"); //keep triggering this event until we've filled the viewport
      }
    }



  });

  function load_more() {
    //fetch more data here
    
    for(var i = 0;i<= page;i++){
        count++;
        $datatable.row.add([
        count + '.1',
        count + '.2 (new loaded)'
      ]).draw(false);
    }
  }

  //trigger initial fetch
  $(window).trigger("fetchmore");
});
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
</head>

<body>
  <table id="myTable" class="display">
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1.1</td>
        <td>1.2 (initial row)</td>
      </tr>
      <tr>
        <td>2.1</td>
        <td>2.2 (initial row)</td>
      </tr>
      <tr>
        <td>3.1</td>
        <td>3.2 (initial row)</td>
      </tr>
    </tbody>
  </table>
</body>