使用带分页和排序的jjax动态地将行添加到datatable

时间:2015-06-12 14:39:07

标签: jquery twitter-bootstrap pagination jquery-datatables

我正在努力实现https://almsaeedstudio.com/themes/AdminLTE/pages/tables/data.html - “具有完整功能的数据表”

当我静态添加tbody时,分页和排序工作正常但是当我使用下面给出的jquery添加tbody时,会添加行但分页和排序失败。

HTML

<table id="tblItems">
    <thead>
        <tr>
            <th>code</th>
            <th>Name</th>
            <th>Description</th>
            <th>Image</th>
            <th>Parent</th>
            <th>Location</th>
            <th>Category</th>
        </tr>
    </thead>
</table>

jquery的

$(document).ready(function() {
    $('#tblItems').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });
    $('#tblItems').append('<tbody><tr><td>asdsa34id</td><td> asdsa34id </td><td>asdsa34id </td><td> asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td></tr></tbody>');
});

https://jsfiddle.net/techjerk2013/vwpsxhaL/

更新代码

虽然响应中有数据,但更新后的代码不会填充表格。虽然我将deferRender设置为true,但数据表仍为空。

$(document).ready(function() {
    PopulateItemsTable();
    BindTable();
});

function BindTable() {
    $("#tblItems").DataTable({
        "deferRender": true,
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });
}

function PopulateItemsTable() {
    var txt = "";
    $.ajax({
        type: "POST",
        url: "Item.aspx/Search",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var jsonObject = JSON.parse(response.d);
            if (jsonObject) {
                var len = jsonObject.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if (jsonObject[i].Id) {
                            Id = jsonObject[i].Id;
                        }
                        else {
                            Id = '';
                        }
                        if (jsonObject[i].Name) {
                            Name = jsonObject[i].Name;
                        }
                        else {
                            Name = '';
                        }
                        if (jsonObject[i].Description) {
                            Description = jsonObject[i].Description;
                        }
                        else {
                            Description = '';
                        }
                        if (jsonObject[i].Image) {
                            Image = jsonObject[i].Image;
                        }
                        else {
                            Image = '';
                        }
                        if (jsonObject[i].Parent) {
                            Parent = jsonObject[i].Parent;
                        }
                        else {
                            Parent = '';
                        }
                        if (jsonObject[i].Location) {
                            Location = jsonObject[i].Location;
                        }
                        else {
                            Location = '';
                        }
                        Category = '';

                        txt += "<tr><td>" + Id + "</td><td>" + Name + "</td><td>" + Description + "</td><td>" + Image + "</td><td>" + Parent + "</td><td>" + Location + "</td><td>" + Category + "</td></tr>";
                        $('#tblItems').append('<tbody>' + txt + '</tbody>');
                    }
                }
                else {
                    $("#tblItems").append("No records found");
                }

            }
        },
        failure: function () {
            $("#tblItems").append(" Error when fetching data please contact administrator");
        }
    });
}

答案

以下人员的帮助会得到解答,下面的代码会按预期运行。

<script type="text/javascript">

    var myTable;

    $(document).ready(function () {
        BindItemTable();
        PopulateItemsTable();

    });

    function BindItemTable() {
        myTable = $("#tblItems").DataTable({
            "deferRender": true,
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "sDom": 'lfrtip'
        });
    }

    function PopulateItemsTable() {
        $.ajax({
            type: "POST",
            url: "ItemManagement.aspx/SearchIdList",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var jsonObject = JSON.parse(response.d);
                var result = jsonObject.map(function (item) {
                    var result = [];
                    result.push(item.Id);
                    result.push(item.Name);
                    result.push(item.Description);
                    result.push(item.Image);
                    result.push(item.Parent);
                    result.push(item.Location);
                    result.push("");
                    return result;
                });
                myTable.rows.add(result);
                myTable.draw();
            },
            failure: function () {
                $("#tblItems").append(" Error when fetching data please contact administrator");
            }
        });
    }
</script>

3 个答案:

答案 0 :(得分:9)

不要直接将行添加到表标记中,而是将其添加到DataTable实例,然后使用.draw()方法。无论如何,添加到DataTable实例将在内部将其添加为tbody。这样的事情应该做

var mytable = $('#tblItems').DataTable({
    "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
});
mytable.row.add(['asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id']);
mytable.draw();

这是一个演示 https://jsfiddle.net/dhirajbodicherla/vwpsxhaL/1/

同时阅读其文档中的how to add rows to DataTable以供进一步参考

更新

您可以使用rows.add()(复数)并执行此类操作

var jsonObject = JSON.parse(response.d);
var result = jsonObject.map(function(item){
  var result = [];
  result.push(item.Id); 
  // .... add all the values required
  return result;
});
myTable.rows.add(result); // add to DataTable instance
myTable.draw(); // always redraw
var myTable;
$(document).ready(function() {
  myTable = $("#tblItems").DataTable({
    "deferRender": true,
    "paging": true,
    "lengthChange": false,
    "searching": false,
    "ordering": true,
    "info": true,
    "autoWidth": false,
    "sDom": 'lfrtip'
  });
  PopulateItemsTable();
});

function PopulateItemsTable() {
  $.ajax({
    type: "POST",
    url: "Item.aspx/Search",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
      var jsonObject = JSON.parse(response.d);
      var result = jsonObject.map(function(item){
        var result = [];
        result.push(item.Id); 
        // .... add all the values required
        return result;
      });
      myTable.rows.add(result); // add to DataTable instance
      myTable.draw(); // always redraw
    }
  });
}

答案 1 :(得分:2)

如果您使用jQuery修改表格html而不是插件提供的api,则必须再次调用插件,以便根据修改后的html重新实例化。

$(document).ready(function() {
    $('#tblItems').append('<tbody><tr><td>asdsa34id</td><td> asdsa34id </td><td>asdsa34id </td><td> asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td></tr></tbody>');

    $('#tblItems').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });

});

演示 https://jsfiddle.net/8hyr08xb/

根据编辑过的问题进行更新

试试这个

function PopulateItemsTable() {
    var txt = "";
    $.ajax({
        type: "POST",
        url: "Item.aspx/Search",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var jsonObject = JSON.parse(response.d), html = [];
            if (jsonObject) {
                var len = jsonObject.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if (jsonObject[i].Id) {
                            Id = jsonObject[i].Id;
                        }
                        else {
                            Id = '';
                        }
                        if (jsonObject[i].Name) {
                            Name = jsonObject[i].Name;
                        }
                        else {
                            Name = '';
                        }
                        if (jsonObject[i].Description) {
                            Description = jsonObject[i].Description;
                        }
                        else {
                            Description = '';
                        }
                        if (jsonObject[i].Image) {
                            Image = jsonObject[i].Image;
                        }
                        else {
                            Image = '';
                        }
                        if (jsonObject[i].Parent) {
                            Parent = jsonObject[i].Parent;
                        }
                        else {
                            Parent = '';
                        }
                        if (jsonObject[i].Location) {
                            Location = jsonObject[i].Location;
                        }
                        else {
                            Location = '';
                        }
                        Category = '';

                        html.push("<tr><td>" + Id + "</td><td>" + Name + "</td><td>" + Description + "</td><td>" + Image + "</td><td>" + Parent + "</td><td>" + Location + "</td><td>" + Category + "</td></tr>");
                    }

                    $('#tblItems')
                       .append('<tbody>' + html.join('') + '</tbody>')
                       .DataTable({
                          "paging": true,
                          "lengthChange": false,
                          "searching": false,
                          "ordering": true,
                          "info": true,
                          "autoWidth": false,
                          "sDom": 'lfrtip'
                   });
                }
                else {
                    $("#tblItems").append("No records found");
                }

            }
        },
        failure: function () {
            $("#tblItems").append(" Error when fetching data please contact administrator");
        }
    });
}

答案 2 :(得分:0)

相信我,我没有编写长行代码就完成了以上所有工作

对我来说,解决方案非常简单快捷。 现在,要使数据表与您的Ajax请求一起使用,您必须先调用该请求,然后再使用数据表 例子

enter image description here

请注意,您不必在调用ajax之前先调用DataTable,该表需要将数据馈送到表主体中

<tbody class="load-transactions"> and append using jquery for the rest

enter image description here

只需尝试一下。待会儿谢谢我。