刷新jQuery数据表格表格

15

有很多关于这个问题的提问,但我从未找到适合我的答案。我有一个简单明了的HTML表格,其body正在通过AJAX调用填充行。 然后我想使用DataTable插件更新表格,但它不起作用。 我有一个长这样的HTML表格:

<table id="myTable">
  <thead>
     <tr>
          <th>1</th>
          <th>2</th>
          <th>3</th>
          <th>4</th>
          <th>5</th>
     </tr>
  </thead>
  <tbody>
  </tbody>
</table>

在我的jQuery页面加载中

$(document).ready(function(){
        var oTable = $('#myTable').dataTable({
            "aoColumns": [
              { "bSortable": false },
              null, null, null, null
            ]
        });
});

最后是我的下拉列表改变函数

$("#dropdownlist").on("change", function () {
        $("tbody").empty();
            $.ajax({
                type: "POST",
                url: "@Url.Action("ActionHere", "Controller")",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, item) {
                        $("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
                    });
                }
            })
        var oTable = $('#myTable').dataTable(); // Nothing happens
        var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
                "aoColumns": [
                  { "bSortable": false },
                  null, null, null, null
                ]
            });
        });

这里的“追加”等操作已经被修改,简化了流程,所以不要过于关注。基本问题是如何更新表格,我可以通过AJAX添加新数据到表格中,但datatable插件不能实时更新。我尝试了其他方法,比如:

.fnDraw(false);

但它没有起作用。当我使用

fnReloadAjax()

时,会出现JSON错误。有什么提示可以刷新表格吗?

6个回答

27

试试这个

首先要清空表格,因为你最初已经初始化了表格。

$('#myTable').dataTable().fnDestroy();

然后在ajax成功后重新初始化表格。

$('#myTable').dataTable();

就像这样

$("#dropdownlist").on("change", function () {
        $("tbody").empty();
            $.ajax({
                type: "POST",
                url: "@Url.Action("ActionHere", "Controller")",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, item) {
                        $("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
                    });
                }
            })
       $('#myTable').dataTable().fnDestroy();
       $('#myTable').dataTable({ // Cannot initialize it again error
                "aoColumns": [
                  { "bSortable": false },
                  null, null, null, null
                ]
            });
        });

演示


经过一段时间的努力,我终于让它正常工作了。我的AJAX代码有点太复杂了,而且似乎存在很多浏览器兼容性问题,但目前它运行良好。 - HenrikP
请在其中添加此设置: "bDeferRender": true - user2930100

3

谢谢,这很有帮助。在您的datatable中使用"destroy: true,",当您想重新加载时,使用table.ajax.reload(); - hYk

2
var table =  $('#product_table').DataTable({
    "bProcessing": true,
    "serverSide": true,
    responsive: true,
    "ajax": {
        url: get_base_url + "product_table", // json datasource
        type: "post", // type of method  ,GET/POST/DELETE
        error: function () {
            $("#employee_grid_processing").css("display", "none");
        }
    }
});

//call this funtion 
$(document).on('click', '#view_product', function () {
  table.ajax.reload();
});

1
我曾经做过与此相关的事情...以下是一个包含所需内容的示例JavaScript。这里有一个演示: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table 
var manageMemberTable;

function updateMember(id = null) {
    if(id) {
        // click on update button
        $("#updatebutton").unbind('click').bind('click', function() {
            $.ajax({
                url: 'webdesign_action/update.php',
                type: 'post',
                data: {member_id : id},
                dataType: 'json',
                success:function(response) {
                    if(response.success == true) {                      
                        $(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                            '</div>');

                        // refresh the table

                        manageMemberTable.ajax.reload();

                        // close the modal
                        $("#updateModal").modal('hide');

                    } else {
                        $(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                            '</div>');

                        // refresh the table                        
                        manageMemberTable.ajax.reload();

                        // close the modal
                        $("#updateModal").modal('hide');
                    }
                }
            });
        }); // click remove btn
    } else {
        alert('Error: Refresh the page again');
    }
}

1
从版本1.10.0开始,您可以使用ajax.reload() API。
var table = $('#myTable').DataTable();
table.ajax.reload();

记住要使用 $('#myTable').DataTable() 而不是 $('#myTable').dataTable()

0
在你的ajax调用中加入cache=false,例如:
$("#dropdownlist").on("change", function () {
        $("tbody").empty();
            $.ajax({
                type: "POST",
                cache: false, // THIS IS THE LINE YOU SHOULD ADD
                url: "@Url.Action("ActionHere", "Controller")",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, item) {
                        $("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
                    });
                }
            })
       $('#myTable').dataTable().fnDestroy();
       $('#myTable').dataTable({ // Cannot initialize it again error
                "aoColumns": [
                  { "bSortable": false },
                  null, null, null, null
                ]
            });
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接