Appending Rows to a DataTables Grid

2019-07-26 22:56发布

问题:

I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:

$("#Grid").DataTable({
   stateSave: true,
   fixedHeader: true,
   rowReorder: true,
   .
   .
   columnDefs: [
      { orderable: false, className: "seq-cell", targets: 0 },
      { orderable: false, targets: "_all" }
   ]
})
.on("row-reordered", function (e, diff, edit) {
   for (var i = 0; i < diff.length; i++)
   {
       ..
   }
});

I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       var $body = $("#Grid tbody");
       $body.append(d);
    }
});

The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?

回答1:

Use row.add() API method to add a new row instead of appending to the table body.

If d contains string in the following format <tr>...</tr>, you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.

For example:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().row.add($(d).get(0)).draw();
    }
});

See this example for code and demonstration.



回答2:

The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add(). The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.

However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy (destroy()) the Datatables table, append your data then re-init Datatables. For example:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().destroy();
       var $body = $("#Grid tbody");
       $body.append(d);

       $("#Grid").DataTable({
       stateSave: true,
       fixedHeader: true,
       rowReorder: true,
       .
       .
       columnDefs: [
          { orderable: false, className: "seq-cell", targets: 0 },
          { orderable: false, targets: "_all" }
       ]
    })

    }
});