weixin_33743703 2017-11-13 01:53 采纳率: 0%
浏览 31

数据表标题列ajax

I fill a datatable via ajax with the code below, but I need to rename the columns with the ajax return as well. How to do to rename the columns of the datatable with return json?

var table = $('#my_table').dataTable({
    serverSide: true,
    searching: false,
    bAutoWidth:false,
    bFilter: true,
    bLengthChange: false,
    responsive: true,
    ajax: 'clientes.php',
    dataSrc: 'data',
    columns: [ {"sTitle":"#", "data":"client_id"},{"sTitle":"Name", "data":"client_name"},{"sTitle":"Contact", "data":"client"} ]
});
  • 写回答

1条回答 默认 最新

  • weixin_33749242 2017-11-13 12:10
    关注

    Resolved, thanks to @davidkonrad

       $.getJSON("clients.php, function(json) {
            var keys = Object.keys(json['data'][0]),
                columns = [];
            for (var i=0;i<keys.length;i++) {
                columns.push(
                    { data: keys[i], title: keys[i] }
                );
            }
            var table = $('#my_table').DataTable({
                searching: false,
                bAutoWidth:false,
                bFilter: true,
                bLengthChange: false,
                responsive: true,
                data : json.data,
                columns : columns
            });
        });
    

    PHP

            $clients_sql =
            "
                SELECT
                    *
                FROM
                    client
            ";
        $data = array();
    
        $result = mysqli_query($mysqli, $clients_sql);
        while($row = $result->fetch_array(MYSQLI_ASSOC))
        {
            $id         = $row['client_id'];
            $name       = $row['client_name'];
            $phone      = $row['client_phone'];
            $data[]    = array('ID'=> $id, 'Name'=> $name, 'Phone'=> $phone);
        }
    
        $results['data'] = $data;
        echo json_encode($results);
    
    评论

报告相同问题?