Datatables reload on change event

2019-08-07 04:56发布

问题:

I have a html drop down that initially populates and shows the data table. The data is coming from a json array. Once the drop down is changed i'm getting the reinitialise error and having trouble fixing it.

I've tried the table.ajax.reload and also the table.fnReloadAjax(); I work with datatables off an on so not the greatest with them.

Here is the code:

function Population() {
var table = $('#Population').dataTable();

$("#quickStats").change(function () {

    var optionValue = $("#quickStats").val();
    console.log(optionValue);

    if (optionValue == 1) {
        $("#display").append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="Population">' +            
        '<thead><tr><th>Demographic</th><th>Total</th></thead>'
         + '</table>');


    $('#Population').dataTable({
        "data": usPopulation,
        "bJQueryUI":true,
        "columns": [
            { "data": "Demographic" },
            { "data": "Total" }

        ],
    });
}
    table.ajax.reload();

});
}

回答1:

Try destroying the previous one before creating new:

$('#Population').dataTable().fnDestroy();


 $('#Population').dataTable({
        "data": usPopulation,
        "bJQueryUI":true,
        "columns": [
            { "data": "Demographic" },
            { "data": "Total" }

        ],
    });

or do like this:

var table = $('#Population').dataTable({
            "data": usPopulation,
            "bJQueryUI":true,
            "columns": [
                { "data": "Demographic" },
                { "data": "Total" }

            ],
        });

table.draw();