我通过ajax用下面的代码填充数据表,但我还需要用ajax返回重命名列。如何使用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"} ]
});
答案 0 :(得分:0)
解决,感谢@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);