[英]How to use dataTable with getelementbyid in html and javascript?
My code 我的密码
<div id = "showData" class="box-body"></div>
<script>
$(document).ready(function(){
$.ajax({
url: "http://127.0.0.1:4220/pipeline/v1/bpwi/",
success: function (data) {
var col = [];
var _data = JSON.parse(data)
for (var i = 0; i < _data.length; i++) {
for (var key in _data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
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]];
}
}
var divContainer = document.getElementById("showData");
//var divContainer = $("#showData").dataTable();
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
})
})
</script>
This code will get me a nice table with header and data dynamically inserted but without a pagination. 这段代码将为我提供一个不错的表,该表具有动态插入的标头和数据,但没有分页。 I would love to add a pagination and for that I already tried 我想添加一个分页,为此我已经尝试过
var divContainer = document.getElementById("showData").dataTable();
but nothing happen. 但什么也没发生。 There was no table at all. 根本没有桌子。 I read the example for dataTable here and it looks like I have to manually write the header first in the div
and table
section. 我在这里阅读了dataTable的示例,看来我必须首先在div
和table
部分中手动编写标头。
Is there a way that I can use dataTable with my current code? 有没有办法可以在当前代码中使用dataTable?
Thank you for your help 谢谢您的帮助
Here's a working datatables with ajax call, you just need to allow cross-origin so before running, install this plugin and here to undestand why 这是一个带有ajax调用的工作数据表,您只需要允许跨域访问,因此在运行之前,请安装此插件,并在此处理解为什么
$(document).ready(function() { $('#example').DataTable({ "ajax": "https://datatables.net/examples/ajax/data/arrays.txt" }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"> <html> <body> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Extn.</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Extn.</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> </table> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.