Как перезагрузить данные в существующей dataTable ()? - PullRequest
0 голосов
/ 01 октября 2019

У меня есть таблица, которая уже отображается на экране. Если пользователь добавил новую строку или отредактировал существующую, то новый набор данных будет возвращен с помощью 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>

По некоторым причинам текущие данные не удаляются. Я хотел бы удалить все существующие данные и перезагрузить новые данные в таблице. Если у кого-то есть предложения, пожалуйста, дайте мне знать.

1 Ответ

1 голос
/ 03 октября 2019
<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. -->


Ваш URL-адрес ajax должен будет возвращать данные в формате 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()

После изменения данных вы можете использовать table_1.draw () или table_1.reload (), как предложено @NawedKahn, - в зависимости от вашего варианта использования.

Тонны полезногофункциональные возможности можно найти в Документах ниже

Все, что вы можете делать с объектами данных: https://datatables.net/reference/api/

Все параметры данных: https://datatables.net/reference/option/

Просмотрите эти ссылки, прежде чем пытаться создать какую-либо функциональность, возможно, она уже существует.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...