javascript - 如何重新加载现有dataTable()中的数据?

标签 javascript jquery datatable datatables

我的表格已显示在屏幕上。如果用户添加新行或编辑现有行,则新的数据集将随 ajax 返回。检索数据后,我想清除 tbody 中的现有记录并刷新/重新加载 dataTable 。这是我的代码示例:

var statusData = {
  479664: {
    "author": "JH2423",
    "up_to": "09/30/2017",
    "status": "Closed",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Slow",
    "status_id": "479664"
  },
  479665: {
    "author": "KK2342",
    "up_to": "09/30/2017",
    "status": "Approved",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Close",
    "status_id": "479664"
  },
  479666: {
    "author": "DD7822",
    "up_to": "09/30/2017",
    "status": "Close",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Process",
    "status_id": "479666"
  },
  479667: {
    "author": "YU8343",
    "up_to": "09/30/2017",
    "status": "Declined",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Warrning",
    "status_id": "479667"
  },
  479668: {
    "author": "MMSD3",
    "up_to": "09/30/2017",
    "status": "Participating",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Approved",
    "status_id": "479668"
  }
};

buildDataTable('tbl-status', false, 2, false, true, true, []);

function buildDataTable(tblID, lengthChange, pageLen, searchBar, infoSection, pagingInfo, arrOrder) {
  var table = $("#" + tblID),
    arrSort = [];

  if (arrOrder.length) {
    arrSort.push(arrOrder); // arrOrder example: [1, "desc"] or [4, "asc"]. First element is column (first col starts from 0) and second is order by direction.
  }

  $(table).DataTable({
    lengthChange: lengthChange,
    pageLength: pageLen,
    lengthMenu: [
      [10, 15, 20, 25, 50, -1],
      [10, 15, 20, 25, 50, "All"]
    ],
    order: arrSort,
    searching: searchBar,
    info: infoSection,
    paging: pagingInfo
  });
}

$("#load").on("click", function() {
  var container = $("#status-container"), // Clear out existing table.
    table = $("<table>").addClass("table").prop("id", "tbl-status"),
    thead = $("<thead><tr><th>Reason</th><th>As Of</th><th>Up To</th><th>Author</th><th>Date</th><th>Status</th><th class='text-center'>Status</th></tr></thead>"),
    tbody = $("<tbody>");

  if ($.isEmptyObject(statusData)) {
    var tr = $('<tr><td colspan="7">No records were found.</td></tr>');
    tbody.append(tr);
  } else {
    for (key in statusData) {
      var btnName = statusData[key].current == true ? "Change" : "Edit";
      var tr = $('<tr>');
      tbody.append(tr);
      tr.append($('<td>').text(statusData[key].reason));
      tr.append($('<td>').text(statusData[key].as_of));
      tr.append($('<td>').text(statusData[key].up_to));
      tr.append($('<td>').text(statusData[key].author));
      tr.append($('<td>').text(statusData[key].date));
      tr.append($('<td>').text(statusData[key].status));
      tr.append($('<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="' + statusData[key].status_id + '" data-current="' + statusData[key].current + '"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> ' + btnName + '</button></td>'));
    }
  }
  
  $("#tbl-agency-status").remove(); // Remove existing table.
  table.append([thead, tbody]);
  container.append(table);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.html5.min.js"></script>
<button type="button" name="load" id="load">Load New Data</button>
<div class="card mt-4">
  <div class="card-header card-bg-custom">
    <h5 class="text-center">Status</h5>
  </div>
  <div class="card-body">
    <div class="table-responsive" id="status-container">
      <table class="table" id="tbl-status">
        <thead>
          <tr>
            <th>Reason</th>
            <th>As Of</th>
            <th>Up To</th>
            <th>Author</th>
            <th>Date</th>
            <th>Status</th>
            <th class="text-center">Status</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Failure</td>
            <td>09/11/2019</td>
            <td>10/31/2019</td>
            <td>System</td>
            <td>10/01/2019</td>
            <td>Conditional</td>
            <td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505552" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button></td>
          </tr>
          <tr>
            <td>Initial</td>
            <td>06/12/2017</td>
            <td>09/30/2017</td>
            <td>MM434</td>
            <td>06/23/2017</td>
            <td>Participating</td>
            <td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="479664" data-current="false"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
          </tr>
          <tr>
            <td>Reporting</td>
            <td>07/11/2019</td>
            <td>08/31/2019</td>
            <td>System</td>
            <td>10/01/2019</td>
            <td>Testing</td>
            <td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505551" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

由于某种原因,当前数据未被删除。我想删除所有现有数据并重新加载表中的新数据。如果有人有建议请告诉我。

最佳答案

<script> //I usually put the script section at the end of head tag

var table_1; //declare your table var here and initialize as a datatable inside document ready below.

$(document).ready(function() {

  table_1 = $('#table_1').DataTable( {
    dom: "Bfrtip",
    ajax: {
        url: "/get-data",  //path where json data will be served from. ex: get-data.php or my-data.json
        type: "POST"  //use POST to not have to deal with url encoding various characters
    },      
    serverSide: true,
    searchDelay: 2000,  // use this to throttle ajax requests when typing in search input 
    processing: true, // optional visual indicator that a search has been sent to backend
    lengthMenu: [ 10, 25, 50, 75, 100 ], // define per page limits. first value will be the default
    buttons: [
        "pageLength" // per page drop down button. i usually override/extend the default button
    ],      
    columns: [ // column definitions of json data fields
      { data: "status_id", title: "ID", width: "1%" },  // width:1% makes col width as small as possible
      { data: "status", title: "Status(hidden)", visible:false }, //visible:false hides column but allows you access to field data
      { data: "reason", title: "Reason and Status", render: function ( data, type, row ) { //render allows combining of fields into single column
        return data + ' <small>('+row.status+')</small>'; // data will be reason value. row.status is how you reference status value
      } },
      { data: "current", title: "Current", searchable:false }, //searchable: false set this field to not be used in search
      { data: null, title: "Button", render: function ( data, type, row ) { // use data:null if you need to render stuff in a column that does not necessarily need to be tied to a specific data value
        if(row.current){
          return '<button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="'+ row.status_id +'" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button>';
        }
        else{
          return '<button>Different Button</button>';
        }
      } },
    ],
    rowId: 'status_id' //sets the tr row id to the value in this column. useful for DOM and other manipulation later
  } );
}

</script>

<table id="table_1" class="table table-striped table-bordered table-sm" style="width:100%"></table>

<!-- If you define the title attributes in json column definitions above 
then you don't need to create html table headers/footers. 
Just an empty table tag will do. -->


您的 ajax url 需要返回 JSON 格式的数据和对象数组:

[
  {
    "author": "KK2342",
    "up_to": "09/30/2017",
    "status": "Approved",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Close",
    "status_id": "479664"
  },
  {
    "author": "DD7822",
    "up_to": "09/30/2017",
    "status": "Close",
    "as_of": "06/12/2017",
    "date": "06/23/2017",
    "current": false,
    "reason": "Process",
    "status_id": "479666"
  }
]

首先,创建一个包含上述内容的名为 testing.json 的文件。然后将上面示例中的 table_1 ajax-url 替换为“/your_folder_path/testing.json”。现在应该加载此数据表。

要访问数据,您只需调用:

table_1.data(); // datatables object
//OR
table_1.data().toArray(); // a simple array of objects with each rows data you can loop through

有关操作每行数据的文档可以在这里找到:https://datatables.net/reference/api/row().data()

修改数据后,您可以按照 @NawedKahn 的建议使用 table_1.draw() 或 table_1.reload() - 具体取决于您的用例。

下面的文档中可以找到大量有用的功能

使用数据表对象可以的一切: https://datatables.net/reference/api/

所有数据表选项: https://datatables.net/reference/option/

在尝试构建任何类型的功能之前浏览这些链接,它可能已经存在。

关于javascript - 如何重新加载现有dataTable()中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58190419/

相关文章:

javascript - 如何更改 tr 的背景颜色

javascript - 单击选项卡时,卡片选项卡与文本不对应?

javascript - 名称属性中带有方括号的输入的 jQuery 选择器

c# - DataTable 到可读文本字符串

asp.net - 使用 jquery 将数据表转为 Json

javascript - 在 java 和 javascript 之间共享文件和数据的安全方法

javascript - 带有 promise 的链式 AngularJS 循环

javascript - jQuery Cycle With Rotate 不适用于 Bootstrap

当 html 在 JSON 数据包中传递时,Javascript 错误

c# - 使用百分号在 DataTable 中添加计算列的表达式