jQuery DataTables - Cannot reinitialise DataTable

前端 未结 1 1827
广开言路
广开言路 2021-01-22 21:41

I\'m making a statements page in a spring 4.x application using jQuery DataTables to render the statements.

I have the following object returned by the server after pars

相关标签:
1条回答
  • 2021-01-22 22:22

    SOLUTION 1

    Use ajax.data option to add additional parameters that would be sent to the server.

    That way you don't need to re-initialize the table which makes the code much simple.

    For example:

    $('#example').DataTable({
        ajax: {
            url: "/script.php",
            data: function(d){
                d.select1 = $('#example-select1').val();            
                d.select2 = $('#example-select2').val();            
            }
        }
    });
    
    $('#example-select1, #example-select2').on('change', function(){
        $('#example').DataTable().ajax.reload(); 
    });
    

    where example-select1, example-select2 are IDs of your drop-downs.

    See this jsFiddle for code and demonstration.

    SOLUTION 2

    Use clear() along with rows.add() to clear the table and add new data for DataTables 1.10+. For DataTables 1.9, use fnClearTable and fnAddData respectively.

    To add data to existing table (for DataTables 1.10+):

    $('#example').DataTable().clear();
    $('#example').DataTable().rows.add(msg.data);
    

    where msg is a variable holding response from the server.

    SOLUTION 3

    Use bDestroy (for DataTables 1.9) or destroy (for DataTables 1.10+) options to destroy any existing table matching the selector and replace with the new options.

    To reinitialize the table (for DataTables 1.10+):

    $('#example').DataTable( {
       "destroy": true,
       "data": msg.data,
       "columns": [
          {"title": "Description"},
          {"title": "Amount" },
          {"title": "Date" }
       ]
    });
    

    where msg is a variable holding response from the server.

    0 讨论(0)
提交回复
热议问题