首页 > 解决方案 > 如何使用数据表将 ajax 结果附加到模态中

问题描述

今天是个好日子!我正在尝试将我的 ajax 结果附加到我的模式内的数据表中。我已经获得了我需要的数据,但它仍然显示数据不可用。

它显示如下:它是这样显示的。

这是我处理结果的ajax成功。

    success: function(result)
    { 
      //console.log(result);
      //$('#viewTable').empty();
      $.each(result, function(index, value){
        console.log(value);

        $('#viewTable').append(
         '<tbody>' + 
             '<tr>' +
                '<td>' + value.qr_code + '</td>' +
                '<td>' + value.reference_no + '</td>' +
                '<td>' + value.brand_name + '</td>' +
                '<td>' + value.model_name + '</td>' +
                '<td>' + value.unitPrice + '</td>' +
             '</tr>' +
          '</tbody>'
          );
      });

这是我的 HTML

        <table id="viewTable" class="table table-striped">
          <thead>
            <tr>
              <th>Barcode</th>
              <th>Reference Number</th>
              <th>Brand Name</th>
              <th>Model Name</th>
              <th>Unit Price</th>
            </tr>
          </thead>
        </table>

注意:当我取消注释“$('#viewTable').empty();” 功能它将删除我的thead(数据表)。

谢谢!

标签: jqueryhtmlajax

解决方案


首先将dataTable对象存储在一个变量中,

var dataTable = $("#viewTable").DataTable();

然后在 ajax 成功时,使用 dataTable.add([" "," ", " "]).draw(),其中 dataTable 是变量名。

要清除数据表,请使用 dataTable.clear();

dataTable.clear().draw();

请参阅下面的代码;

success: function(result) {
  // store your data table object in a variable
  var dataTable = $("#viewTable").DataTable();
  /////////////////////////////////////////////
  dataTable.clear().draw();

  $.each(result, function(index, value) {
    console.log(value);

    // use data table row.add, then .draw for table refresh
    dataTable.row.Add([value.qr_code, value.reference_no, value.brand_name, value.model_name, value.unitPrice]).draw();
  });
}


推荐阅读