json - Datatable.js 从 JSON 数据动态设置列标题
问题描述
我正在使用 Datatabls 通过 ajax 显示表数据。但有时列名不同。所以我用 json 数据从服务器获取它们的数组列表。现在使用空的thead 并希望将实际的列名放在那里。
我的 JS:
$('#DTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "data.php",
"type": "POST",
"dataType": "json",
"dataSrc": "data"
}
});
我的 JSON:
{
"col": [
"A",
"B",
"C",
"D",
"E"
],
"data": [
[
"Umn(i4(5P~",
"wA~W70Vtmj",
"^taMfGgmKC",
"klPx6XrZR*",
"H6ooRlotEB"
],
[
"DrUE)Z234C",
"udN2BJOSpn",
"GWjU3~*hbr",
"IFIk1t1!m(",
"kH*Yypo5)E"
],
[
.........
]
]}
假设我需要使用:
"dataFilter": function(res) {
res.col.....
}
和
"columnDefs": [
{ "title": "My custom title", "targets": 0 }
]
但是我奇怪的数据不是 json 数据类型,我不能使用 res.col 来列出和放置它们,也不知道究竟是如何......
解决方案
好的。我找到了解决方案。也许不是最好的,但它的工作。
// First call standard ajax request for getting column names
$.ajax({
url: "data.php",
type: "POST",
dataType: "json",
success: function(res) {
//put column names into thead
$('#DTable thead tr').empty();
var cols=res.col;
for (var i=0; i<cols.length; i++) {
$('#DTable thead tr').append('<th>'+cols[i]+'</th>');
}
// initialise Datatable
$('#DTable').DataTable({
processing: true,
serverSide: true,
deferRender: true,
ajax: {
url: "data.php",
type: "POST",
dataType: "json",
dataSrc: "data"
}
});
}
});
推荐阅读
- angular - 从角度调用 POST API 得到 CORS 错误,但相同的端点在 .NET 上工作正常
- unity3d - Unity 2D - 跳转功能无法正常工作
- r - 如何在闪亮的服务器中获取多个文件?
- git - 如何解决上游分支的强制推送?
- swift - 快速计算两个日期之间的天数
- r - 如何将此列表元素解码为单个数据帧?
- python - 字典python元组中的索引
- c# - 未找到 Unity 游戏对象
- react-native - 无法安装 react-native-cloudinary-image-display
- core-data - 将 Xcode Boilerplate Core Data/CloudKit 代码与 MVVM 架构相结合