[英]How to convert a dynamic table to a jquery data table?
I am dynamically creating a HTML table from json data . 我正在根据json数据动态创建HTML表。 I then want to convert this table to a datatable.
然后,我想将此表转换为数据表。 But when I try to do this I keep getting an error that reads:
Uncaught TypeError: Cannot read property 'mData' of undefined
但是,当我尝试执行此操作时,我不断收到错误消息:
Uncaught TypeError: Cannot read property 'mData' of undefined
My jquery is: 我的jQuery是:
$(document).ready(function() {
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson.com/bins/1oaye',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
// convert it to a data table
table.setAttribute("id", "example");
$('#example').DataTable();
},
type: 'GET'
});
});
});
How do I create or convert a dynamic table to a data table from json? 如何从JSON创建动态表或将其转换为数据表?
Just having a quick look at the DataTable code and it looks like the likely reason is that you haven't put the <th>
in a <thead>
section. 快速浏览一下DataTable代码,可能的原因似乎是您没有将
<th>
放在<thead>
部分中。 Currently they sit within <tbody>
. 目前,它们位于
<tbody>
。
Here's the updated fiddle... https://jsfiddle.net/8some9a0/1/ 这是更新的小提琴... https://jsfiddle.net/8some9a0/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.