admin管理员组文章数量:1287517
Im trying to create a dynamic data table with jquery and json. Im trying to exact the keys and set them as headers and then the values in the keys as rows in the table.
So far my code is:
<script type="text/javascript">
$('#action-button').click(function() {
$.ajax({
url: '',
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);
},
type: 'GET'
});
});
</script>
but I keep getting an error that reads:
(index):80 Uncaught TypeError: Cannot set property 'innerHTML' of null
My JSON data structure
JSfiddle
How do I create a dynamic data table just based on the json data returned setting everything from the table headers to the values in the table?
Im trying to create a dynamic data table with jquery and json. Im trying to exact the keys and set them as headers and then the values in the keys as rows in the table.
So far my code is:
<script type="text/javascript">
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson./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);
},
type: 'GET'
});
});
</script>
but I keep getting an error that reads:
(index):80 Uncaught TypeError: Cannot set property 'innerHTML' of null
My JSON data structure
JSfiddle
How do I create a dynamic data table just based on the json data returned setting everything from the table headers to the values in the table?
Share Improve this question asked Oct 10, 2016 at 6:32 kevinabrahamkevinabraham 1,4274 gold badges31 silver badges56 bronze badges 2- If 80 is a line number which line is it in your posted code? – mm759 Commented Oct 10, 2016 at 6:35
-
I just changed the last
div
to<div id="showData"></div>
and that seems to fix the problem? See this update to the fiddle – Dhananjay Commented Oct 10, 2016 at 7:14
4 Answers
Reset to default 5I made two modifications in your code and it seems to be working after that.
1) Added a div with id 'showData' after div 'info'.
<div id="showData">
</div>
2) Enclosed $('#action-button').click(function() in $(document).ready(function().
$(document).ready(function() {
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson./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);
},
type: 'GET'
});
});
});
The error says that it expecting a div with id 'showData'.
Firstly for data table you need to create the static header portion. I'm sharing my easiest code here.
<div class="table-responsive" style="margin-top:20px;">
<table id="tblPatientDiagnosed" class="table table-vcenter table-responsive table-condensed table-bordered display">
<thead>
<tr>
<th class="text-center" width="20%">Consultant Id</th>
<th class="text-center" width="30%">Consultant Name</th>
<th class="text-center" width="30%">Patinet Name</th>
<th class="text-center" width="20%">No. of time seen</th>
</tr>
</thead>
</table>
</div>
This is my static head of data-table.
Now in the document ready function you need to initialize it.
var tblPatientDiagnosed = '';
$(document).ready(function() {
tblPatientDiagnosed = $('#tblPatientDiagnosed').DataTable({
"bPaginate": true,
aaSorting:[],
"processing": true,
"sPaginationType": "full_numbers",
});
$("#action-button").on('click',function(){
tblPatientDiagnosed.fnClearTable();//fisrtly clearing data-table data if exist
$.ajax({
type: "POST",
cache: false,
url: "controllers/admin/add_treatment.php",
datatype:"json",
data: postData,
success: function(data) {
var parseData = JSON.parse(result);
var datalength = parseData.length;
for(var i=0; i < datalength; i++){
var staffId = parseData[i].consultant_id;
var staffLength = staffId.length;
for (var j=0;j<6-staffLength;j++) {
staffId = "0"+staffId;
}
staffId = staffPrefix+staffId;
tblPatientDiagnosed.fnAddData([staffId,'data1','data2','data3']);//write the varibale or data you got from ajax
}
}
});
});
fnadddata add row
<html>
<head>
<script>
function createdynamictable(yourdata)
{
//the parameter must be a json data
var parsedata = JSON.parse(yourdata)
var table = document.createElement("table");
for (var i = 0; i <= parsedata.length; i++)
{
tr = table.insertRow(-1);
for (var key in parsedata[0])
{
if (i == 0)
{
//Inserting columns fields to the table
var trCell = tr.insertCell(-1);
trCell.innerHTML = key;
}
else
{
//Inserting table values to the table
var trCell = tr.insertCell(-1);
trCell.innerHTML = parsedata[i-1][key];
}
};
}
var div = document.getElementById("showtable");
div.innerHTML = "";
div.appendChild(table);
}
</script>
</head>
<body>
<div id="showtable"></div>
</body>
</html>
How to generate a table with dynamic column titles and data from ajax JSON response.
//Javascript code
$.ajax({
"url": SitePath + "/Attendance/getEmployeeMonthYearlyReport",
"data": {
MonthYear: $("#txtEmpMonth").val()
},
"type": "GET",
"dataType": "JSON"
}).success(function (response) {
var objData1 = JSON.parse(response);
var myList = objData1.outdata.Table[0];
var tableHeaders = '';
var tableBody = '';
$.each(myList, function (k, v) {
tableHeaders += "<th>" + k + "</th>";
tableBody += "<td>" + v + "</td>";
});
$("#tblid").append('<thead><tr>' + tableHeaders + '</tr></thead>');
$("#tblid").append('<tbody><tr>' + tableBody + '</tr></tbody>');
})
@* Html code *@
<table class="table-striped table-bordered" id="tblid" align="center" width="100%"></table>
本文标签: javascriptHow to create a dynamic jquery data table with json data and ajaxStack Overflow
版权声明:本文标题:javascript - How to create a dynamic jquery data table with json data and ajax? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741273986a2369621.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论