我正在动态绑定来自JSON URL的数据表,并且还动态生成Header但遇到了一些问题。所以请参阅我的代码片段并建议我如何解决它。我正面临着将json数据传递到数据表中的aaData中片段。
$(document).ready(function () {
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var json = response;
var col = [];
var rdata;
$.each(json, function (index, element) {
for (var key in element) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
})
$.each(response, function (index, element) {
rdata = element;
})
var tableHeaders;
$.each(col, function (i, val) {
tableHeaders += "<th>" + val + "</th>";
});
$("#tableDiv").empty();
$("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
$('#displayTable').DataTable({
"aaData": JSON.stringify(rdata),
"bDestroy": true,
"order": [1, "asc"],
});
//$('#displayTable').DataTable(rdata);
},
failure: function (response) {
alert(response)
}
});
});
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="tableDiv"></div>
答案 0 :(得分:1)
我已经生成了动态列并将其传递给数据表,并且工作正常。
$(document).ready(function () {
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var col = [];
var rdata=[];
$.each(response, function (index, element) {
for (var key in element) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
})
for (var i = 0; i < col.length; i++) {
rdata.push({data:col[i]})
}
var tableHeaders="";
$.each(col, function (i, val) {
tableHeaders += "<th>" + val + "</th>";
});
$("#tableDiv").empty();
$("#tableDiv").append('<table id="displaytable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
$('#displaytable').DataTable({
"aaData": response,
"bDestroy": true,
"columns": rdata,
"order": [1, "asc"]
});
},
failure: function (response) {
alert(response)
}
});
});
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="tableDiv"></div>