我尝试使用这段代码来填充我的表,它运行良好。
问题是,我尝试使用数据表的功能对表进行排序或搜索,但我的表正在被清空。
$('#ipcrTable').DataTable({
responsive: true
});
function get_ipcr() {
var userID = <?php echo $_SESSION['id']; ?>;
$.ajax({
type: "POST",
url: "ipcr.php",
dataType: "json",
success: function(results) {
$.each(results, function(i, val) {
$('#ipcrTable tr:last').after('<tr> <td>' + val.dateCreated + '</td><td>' + val.details + '</td></tr>');
});
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="ipcrTable">
<thead>
<tr>
<th>Time Created</th>
<th>Details</th>
</tr>
</thead>
<tbody id="itBody">
</tbody>
</table>
我尝试通过将数据硬编码到表中来填充表,并且 DataTable 工作正常。我不确定为什么,但在使用 DataTable 的搜索和其他功能后,它会删除我的 get_ipcr() 函数打印的数据。
最佳答案
Datatables 不知道更新的 DOM 内容,因此您应该使用 DataTables api 方法使用 row.add()
更新表格其次是 draw()
重绘表格。这是一个片段演示:
var table = $('#ipcrTable').DataTable({
responsive: true
});
function get_ipcr() {
var results = [
{"dateCreated" : "2018-08-29", "details" : "today!"},
{"dateCreated" : "2018-07-04", "details" : "july 4th"},
{"dateCreated" : "2019-03-20", "details" : "spring equinox"}
];
$.each(results, function(i, val) {
table.row.add([val.dateCreated,val.details]);
});
table.draw();
}
get_ipcr()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="ipcrTable">
<thead>
<tr>
<th>Time Created</th>
<th>Details</th>
</tr>
</thead>
<tbody id="itBody">
</tbody>
</table>
在您自己的代码中它可能看起来像这样:
var table = $('#ipcrTable').DataTable({
responsive: true
});
function get_ipcr() {
var userID = <?php echo $_SESSION['id']; ?>;
$.ajax({
type: "POST",
url: "ipcr.php",
dataType: "json",
success: function(results) {
$.each(results, function(i, val) {
table.row.add([val.dateCreated,val.details]);
});
table.draw(false);
}
});
}
关于jquery - 与数据表功能交互后表清空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068676/