在数据表中插入新行时如何保持滚动位置

时间:2013-03-20 11:54:35

标签: jquery jquery-datatables

我正在使用DataTables插件来处理我的表格。 我想将JSON对象设置为我的表的数据源,并在每次更改此对象时更新内容。

要初始化我的表,我使用以下代码:

     var obj = [];

     // if I make start initialization of the object - the row in a table appears.
     //var obj = [{"Name": "name1", "Id": "id1", "Value":"value1"}];

     var table;

        $(document).ready(function () {

            table = $('#example').dataTable({
                "sPaginationType": "full_numbers",
            "sScrollY": "250px",
            "aaSorting": [],
            "aaData": obj,
            "aoColumns": [
            { "mDataProp": "Name" },
            { "mDataProp": "Id" },
            { "mDataProp": "Value" }
        ]
        });
    }
    );

更新我的JSON对象:

function updateObject() {
    var response = $.ajax({
        type: "GET",
        datatype: "json",
        url: myURL,
        success: function (result) {
            obj = jQuery.parseJSON(result);
            //table.fnDraw(); - tried this but it doesn't work
        }
    });
}

我从服务器获取的JSON数据:

 [{"Name": "name1", "Id": "id1", "Value":"value1"}, 
     {"Name": "name2", "Id": "id2", "Value":"value2"},...]

从服务器获取新数据后是否可以刷新表格内容?

更新

table.fnClearTable();
table.fnAddData(obj, false);
table.fnStandingRedraw();

插入新行后,当前页面也会丢失,当前滚动位置也会丢失。 fnStandingRedraw 方法有助于保持页面位置。但滚动跳转到第一行。有没有办法计算当前滚动位置,以便在更新(http://datatables.net/docs/Scroller/1.0.1/)或其他解决方案后跳回来?

2 个答案:

答案 0 :(得分:1)

我认为这可以帮到你。您应首先删除所有数据并再次添加新数据,文档为here

table.fnClearTable().fnAddData(obj);

答案 1 :(得分:0)

我有类似的情况。 所以最终我解决了这个问题:

function UpdateDatatable(data, $table) {
    $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "../biz/datahandler.ashx",
        data: ({data: data}),
        async: true,
        error: function (xhr, ajaxOptions, thrownError) {
            /* manage the error */
        },
        success: function (dataget) {
            /* maange the success */
            $table.dataTable({
                ...
            })
    });
}
相关问题