简体   繁体   中英

Replace DataTables data and column headers

I can successfully replace the DataTable's data, but not the columns. I am sure I can figure out how to change the column header text, however, this will not work should the column count change. How should one replace both the data and the column header names?

var dataTables;
document.getElementById('query-form').addEventListener('submit', function(event){
    event.preventDefault();
    var url = getUrl();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var json = JSON.parse(this.response);
            if (dataTables) {
                console.log(dataTables)
                dataTables.clear();
                dataTables.rows.add(json.results.data);
                //dataTables.columns.add(json.results.columns);
                dataTables.draw();
            }
            else {
                dataTables = $('#datatables').DataTable( {
                    data: json.results.data,
                    columns: json.results.columns,
              } );
            }
        }
    };
    xhttp.open("GET", url);
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhttp.send();
});

You can manage your data call response like data and column array then put my code in your ajax call or any other calls and solve your dynamic column problem in DataTables.

jQuery(document).ready(function() {
    var dataObject = eval('[{"COLUMNS": [{ "title": "Col1"}, { "title": "Col2"}], "DATA":[["RP","1"],["Billy","2"],["GP","3"],["MM","4"]]}]');
    var columns = [];
    $('#demoexample').dataTable({
        "data": dataObject[0].DATA,
        "columns": dataObject[0].COLUMNS
    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM