How do I refresh/reload my DataTable from HTML source

后端 未结 2 921
抹茶落季
抹茶落季 2020-12-21 11:13

I\'m using BackboneJS to populate my table with multiple data sources. You do not need to know Backbone to assist in this question, as the issue is mainly a

相关标签:
2条回答
  • 2020-12-21 12:08

    Use rows().invalidate() to invalidate the data held in DataTables for the selected rows.

    For example, to invalidate all rows using original data source:

    var table = $('#example').DataTable();
    
    table
        .rows()
        .invalidate()
        .draw();
    

    Please note that draw() will reset the table to the fist page. To preserve the page, use draw(false) instead.

    0 讨论(0)
  • 2020-12-21 12:14

    I was searching for an answer to something similar. In my project the table's content is cleared and rewritten is vanilla JavaScript, and DataTables library was only included later in the project. Here's a trimmed down version of how I got it working with help of DataTables's isDataTable()-function.

    The resultsTable is an empty <table>-tag in the beginning and the contents is written and updated in the updateTable()-function. The function is called when Json data is available through asychronous requests. The DataTables was only included later and if it had been in use from the very beginning, then maybe the implementation would be different.

    I hope this is of help to anyone else.

    table.js

    export default class Table {
      constructor(tableId) {
        this.table = document.getElementById(tableId);
      }
      clearTable() {
        this.table.innerHTML = '';
      }
      writeTable(jsonData) {
        // json to html here
        const thead = ....;
        const tbody = ....;
        this.table.appendChild(thead);
        this.table.appendChild(tbody);
      } 
    }
    

    main.js

    import Table from './modules/table.js';
    
    // My class for writing json to html table
    const table = new Table('resultsTable');
    
    // Global variable for holding DataTable-API
    let myDataTable
    
    function updateTable(jsonData) {
      if ($.fn.DataTable.isDataTable(myDataTable)) {
        // Remove DataTable properties, if they are in use
        myDataTable.destroy();
        // Also empty the html table's content
        table.clearTable();
      }
    
      // (Re)Writes html thead and tbody to the table element
      table.writeTable(jsonData);
    
      // (Re)Set the table to use DataTables API
      myDataTable = $('#resultsTable').DataTable();
    }
    
    0 讨论(0)
提交回复
热议问题