简体   繁体   English

如何清空并重新填充jquery数据表?

[英]How to empty and refill jquery datatable?

I have a jquery datatable on my page. 我的页面上有一个jquery数据表。 This datatable is gonna show data based on a request made to my api 该数据表将根据对我的api的请求显示数据

The HTML that I have is like the following: 我拥有的HTML如下所示:

<table id="details" class="table table-bordered table-hover table-striped nowrap hidden display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>&nbsp;</th>
            <th>Patient Full Name</th>
            <th class="hidden">LF</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>&nbsp;</th>
            <th>Patient Full Name</th>
            <th class="hidden">LF</th>
        </tr>
    </tfoot>
    <tbody>
        <tr id="dummytr2"><td style="text-align:center;padding-top:20px;" colspan="7"><p><em>No Data Available</em></p></td></tr>
        </tbody>
</table>

The first <th> is gonna be used to collapse the tr and get the facility (the third <th> or the hidden one) of this patient. 第一个<th>将用于折叠tr并获得该患者的设施(第三个<th>或隐藏的那个)。

I have a dummy <tr> in the table because I don't want to initialize the datatable at the beginning so I don't get the error message that tells me that I can't initialize my datatable twice. 我在表中有一个虚拟的<tr> ,因为我不想在一开始就初始化数据表,所以我不会收到错误消息,告诉我不能两次初始化我的数据表。

The request to my api is gonna be triggered through a bunch of buttons like the following: 对我api的请求将通过一堆类似于以下的按钮触发:

$.ajax({
            url: "https://" + window.myLocalVar + "/api/metrics/GetDetails?metricName=" + metric,
            type: "GET",
            dataType: 'json',
            contentType: 'application/json',
            success: function (requests) {

                if (requests.length > 0) {
                    $("#dummytr2").remove();
                    for (var i = 0; i < requests.length; i++) {
                        var patient_name = requests[i].PatientFullName;
                        var lab_facility = requests[i].LabFacility;

                        tr = '<tr>\
                                    <td class=" details-control"></td>\
                                    <td>' + patient_name + '</td>\                                 
                                    <td class="hidden">' + lab_facility + '</td>\
                                </tr>';

                                $("#details > tbody").append(tr);



                                //click event for each tr
                                $('#details tbody').on('click', 'td.details-control', function () {
                                    var tr = $(this).closest('tr');
                                    var row = table.row(tr);

                                    if (row.child.isShown()) {
                                        // This row is already open - close it
                                        row.child.hide();
                                        tr.removeClass('shown');
                                    } else {
                                        // Open this row
                                        row.child(format(row.data())).show();
                                        tr.addClass('shown');
                                    }
                                });
                        }  
                    }
                // NOT SURE WHY IT IS NOT WORKING    
                $('#details').dataTable().fnDestroy();

                var table = $('#details').DataTable({
                    "scrollX": true,
                    stateSave: true,
                    "columns": [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        { "data": "PatientFullName" },
                        { "data": "LabFacility" }
                        ],
                    "order": [[1, 'asc']]
                });
            },
            error: function (err) {
                if (err) {
                    console.log(err);
                }
            }
        });
    });

function format(d) {
    // `d` is the original data object for the row
    var lf = d.LabFacility;
    if (lf == "") {
        lf = "No Lab Facility"
    }
    // wrapping text is not working???
    return '<div class="table-responsive"><table class="table display" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
         '<tr>' +
            '<td>Lab Facility:</td>' +
            '<td>' + lf + '</td>' +
        '</tr>' +
    '</table></div>';
}

This ajax request is gonna get called each time a button is clicked. 每次单击按钮都会调用此ajax请求。 This means the content of my datatable is going to change each time a button was clicked. 这意味着我的数据表的内容将在每次单击按钮时更改。 I tried to clear and refill it did not work.. I tried to destroy it .. it did not work.. each time I destroy my datatable and execute the script it won't change the content of the table. 我试图清除并重新填充它不起作用..我试图销毁它..它不起作用..每次销毁数据表并执行脚本时,它都不会更改表的内容。

I am not sure what's wrong with my code. 我不确定我的代码有什么问题。 My code works only for the first time.. the second time you click a button, it won't update my datatable. 我的代码仅在第一次时起作用。第二次单击按钮时,它不会更新我的数据表。

Thanks! 谢谢!

You need to: 你需要:

  • empty the table with empty() empty()清空表
  • remove $('#details').dataTable().fnDestroy(); 删除$('#details').dataTable().fnDestroy();
  • add destroy: true option 添加destroy: true选项

For example: 例如:

if (requests.length > 0) {

   // Empty table        
   $('#details').empty(); 

   // ... skipped ... 

   var table = $('#details').DataTable({
      destroy: true,
      // ... skipped ...
   });

   // ... skipped ... 
}

Please see sample of what I was saying in comments above: 请在上面的评论中查看我所说的示例:

 var dataTable_ = null; var init_ = false; var initDataTable = function() { dataTable_ = $('#table').DataTable({ preDrawCallback: function(settings) { }, drawCallback: function(settings) { if (init_ === false) { init_ = true; } }, searching: true, data: [], fnCreatedRow: function(nRow, aData, iDataIndex) { }, scrollY: true, scrollX: true, responsive: false, serverSide: false, autoWidth: false, processing: false, scrollCollapse: false, lengthChange: false, fixedColumns: false, info: false, select: { info: false, items: 'rows' }, dom: '<"toolbar">Bfrtip', orderMulti: false, stripeClasses: ['dt-stripe-1', 'dt-stripe-2'], columns: [{ name: 'test1', data: 'test1', title: 'Test1', type: 'string', orderable: true }, { name: 'test2', data: 'test2', title: 'Test2', type: 'string', orderable: true }, ] }); }; var ajaxFunction = function() { $.ajax({ url: "https://api.myjson.com/bins/7ed89", type: "GET", dataType: 'json', contentType: 'application/json', success: function(data) { if (init_ === false) { initDataTable(); } if (typeof dataTable_ == 'object') { dataTable_.rows().remove().draw(); dataTable_.rows.add(data); dataTable_.draw(); } //console.log(data); } }); }; $('#button').click(function() { ajaxFunction(); }); 
 <link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <table id="table" class="cell-border hover call-list"> </table> <button id="button">Click To Load Data</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM