jquery - 与数据表功能交互后表清空

标签 jquery html ajax datatable

我尝试使用这段代码来填充我的表,它运行良好。

问题是,我尝试使用数据表的功能对表进行排序或搜索,但我的表正在被清空。

$('#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/

相关文章:

javascript - fullpage.js 添加 slider 淡入淡出效果

css - HTML/CSS 文本从 div 顶部对齐

html - 如何将图像插入 HTML Golang 文件?

jquery - 均衡元素高度功能不起作用

javascript - 菜单 - ajax 加载内容的子菜单和事件链接

javascript - 为什么 CKEditor 将自己添加到不应该添加的 div 中?

jquery - FLOT 工具提示放置?

javascript - 将 php 数组传递给 Ajax/jQuery

javascript - jQuery AJAX 调用不起作用,不知道为什么

javascript - 如何通过单击更改字体超棒的图标 - 可折叠文本