的Json --------------------------
{ "data": [
{
"name": "Garrett Winters",
"designation": "Accountant",
"salary": "$170,750",
},
{
"name": "Brielle Williamson",
"designation": "Integration Specialist",
"salary": "$372,000",
}
]
}
HTML -----------------
<script type="text/javascript">
$(document).ready(function() {
$('#empTable').dataTable({
"ajax": "empdata.json",
"async": false,
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
]
});
});
</script>
我没有将列硬编码为名称,名称和工资,而是想阅读JSON并填充列名。有人可以帮助我吗?
答案 0 :(得分:0)
如果响应中的每个对象具有相同的形状,则使用第一个响应的键创建一个columns数组。
var columnNames = Object.keys(response.data[0])
// Or whatever variable the data is in. You call Object.keys()
// with an object and it will return an array of the keys.
//eg. Object.keys({ 'one': 1, 'ball': 2}) will return ['one', 'ball']
var columns = columnNames.map(name => {
return {"data": name}
});
The columns variable would be a dynamic version of your hard coded columns.