使用ajax刷新表格内容后重绘数据表?

发布于 2024-12-10 11:21:39 字数 1362 浏览 0 评论 0原文

我正在使用 Datatables 并在页面上有一个使用 AJAX 刷新表格的按钮。需要明确的是,该表没有使用 ajax 数据源,我们只是在需要时使用 ajax 来刷新它。 Ajax 正在刷新表格所在的 div。我知道我正在失去分页按钮和过滤功能,因为表格需要重新绘制,但我不知道如何将其添加到表格初始化代码中。

数据表代码

var oTable6;
$(document).ready(function() {
    oTable6 = $('#rankings').dataTable( {
        "sDom":'t<"bottom"filp><"clear">',
        "bAutoWidth": false,
        "sPaginationType": "full_numbers",
        "aoColumns": [ 
            { "bSortable": false, "sWidth": "10px" },
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ]

    });
});

ajax 代码是这样的

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
        function( data ) { 
            $("#ajaxresponse").html(data);
        });
});

我尝试过但它不起作用

"fnDrawCallback": function() {
    function( data ) { 
        $("#ajaxresponse").html(data);
    };
},

I am using Datatables and have a button on the page that refreshes the table using AJAX. To be clear the table isn't using an ajax source of data, we are just using ajax to refresh it only when needed. Ajax is refreshing the div which the table is wrapped in. I know i'm losing my pagination buttons and filtering capability because the table needs to be redrawn but i'm not sure how to add this into the table initialization code.

Datatables code

var oTable6;
$(document).ready(function() {
    oTable6 = $('#rankings').dataTable( {
        "sDom":'t<"bottom"filp><"clear">',
        "bAutoWidth": false,
        "sPaginationType": "full_numbers",
        "aoColumns": [ 
            { "bSortable": false, "sWidth": "10px" },
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ]

    });
});

The ajax code is this

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
        function( data ) { 
            $("#ajaxresponse").html(data);
        });
});

I tried this but it didn't work

"fnDrawCallback": function() {
    function( data ) { 
        $("#ajaxresponse").html(data);
    };
},

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

羅雙樹 2024-12-17 11:21:39

看来您可以使用 API 函数

  • 清除表格 ( fnClearTable )
  • 将新数据添加到表格 ( fnAddData )
  • 重绘表格 ( fnDraw )

http: //datatables.net/api

更新

我猜你正在使用DOM 数据源(用于服务器端处理)来生成表。我一开始并没有真正明白这一点,所以我之前的答案对此不起作用。

要使其工作而无需重写服务器端代码:

您需要做的是完全删除旧表(在 dom 中)并将其替换为 ajax 结果内容,然后重新初始化数据表:

// in your $.post callback:

function (data) {

    // remove the old table
    $("#ajaxresponse").children().remove();

    // replace with the new table
    $("#ajaxresponse").html(data);

    // reinitialize the datatable
    $('#rankings').dataTable( {
    "sDom":'t<"bottom"filp><"clear">',
    "bAutoWidth": false,
    "sPaginationType": "full_numbers",
        "aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

    } 
    );
}

It looks as if you could use the API functions to

  • clear the table ( fnClearTable )
  • add new data to the table ( fnAddData)
  • redraw the table ( fnDraw )

http://datatables.net/api

UPDATE

I guess you're using the DOM Data Source (for server-side processing) to generate your table. I didn't really get that at first, so my previous answer won't work for that.

To get it to work without rewriting your server side code:

What you'll need to do is totally remove the old table (in the dom) and replace it with the ajax result content, then reinitialize the datatable:

// in your $.post callback:

function (data) {

    // remove the old table
    $("#ajaxresponse").children().remove();

    // replace with the new table
    $("#ajaxresponse").html(data);

    // reinitialize the datatable
    $('#rankings').dataTable( {
    "sDom":'t<"bottom"filp><"clear">',
    "bAutoWidth": false,
    "sPaginationType": "full_numbers",
        "aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

    } 
    );
}
想你的星星会说话 2024-12-17 11:21:39

尝试使用 bDestroy:true 销毁数据表,如下所示:

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
            function( data ) { 

                $("#ajaxresponse").html(data);

                oTable6 = $('#rankings').dataTable( {"bDestroy":true,
                    "sDom":'t<"bottom"filp><"clear">',
                    "bAutoWidth": false,
                    "sPaginationType": "full_numbers",
"aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

} 
);
            });

});

bDestroy: true 将首先销毁与该选择器关联的数据表实例,然后再重新初始化新的选择器。

Try destroying the datatable with bDestroy:true like this:

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
            function( data ) { 

                $("#ajaxresponse").html(data);

                oTable6 = $('#rankings').dataTable( {"bDestroy":true,
                    "sDom":'t<"bottom"filp><"clear">',
                    "bAutoWidth": false,
                    "sPaginationType": "full_numbers",
"aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

} 
);
            });

});

bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.

怕倦 2024-12-17 11:21:39

我不知道为什么。但

oTable6.fnDraw();

对我有用。我把它放在下一行。

I'm not sure why. But

oTable6.fnDraw();

Works for me. I put it in the next line.

深爱成瘾 2024-12-17 11:21:39

使用这个:

var table = $(selector).dataTables();
table.api().draw(false);

var table = $(selector).DataTables();
table.draw(false);

Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);
时间你老了 2024-12-17 11:21:39

对于现代 DataTables(1.10 及更高版本)的用户,本页上的所有答案和示例均适用于旧 api,而不是新 api。我很难找到更新的示例,但最终找到了 这个 DT 论坛帖子(TL ;对于大多数人来说,DR)这使我想到了这个简洁的示例

当我终于注意到紧邻 html 字符串的 $() 选择器语法后,示例代码对我有用。您必须添加一个节点而不是字符串。

这个例子确实值得一看,但是,本着 SO 的精神,如果您只想查看一段有效的代码片段:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

细心的读者可能会注意到,因为我们只添加一行数据,即 table.row。 add(...) 应该也能工作并且对我有用。

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.

说谎友 2024-12-17 11:21:39

这对我有用

var dataTable = $('#HelpdeskOverview').dataTable();

var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
   dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();

This works for me

var dataTable = $('#HelpdeskOverview').dataTable();

var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
   dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();
墨小沫ゞ 2024-12-17 11:21:39

在初始化中使用:

"fnServerData": function ( sSource, aoData, fnCallback ) {
                    //* Add some extra data to the sender *
                    newData = aoData;
                    newData.push({ "name": "key", "value": $('#value').val() });

                    $.getJSON( sSource, newData, function (json) {
                        //* Do whatever additional processing you want on the callback, then tell DataTables *
                        fnCallback(json);
                    } );
                },

然后只需使用:

$("#table_id").dataTable().fnDraw();

fnServerData 中重要的是:

    newData = aoData;
    newData.push({ "name": "key", "value": $('#value').val() });

如果您直接推送到 aoData,则在您第一次绘制表格时更改是永久性的,并且 fnDraw 不会按照您想要的方式工作。

In the initialization use:

"fnServerData": function ( sSource, aoData, fnCallback ) {
                    //* Add some extra data to the sender *
                    newData = aoData;
                    newData.push({ "name": "key", "value": $('#value').val() });

                    $.getJSON( sSource, newData, function (json) {
                        //* Do whatever additional processing you want on the callback, then tell DataTables *
                        fnCallback(json);
                    } );
                },

And then just use:

$("#table_id").dataTable().fnDraw();

The important thing in the fnServerData is:

    newData = aoData;
    newData.push({ "name": "key", "value": $('#value').val() });

if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.

离笑几人歌 2024-12-17 11:21:39

这就是我用 ajax 检索到的数据填充表的方式(不确定这是否是最佳实践,但感觉很直观并且效果很好):

/* initialise table */
oTable1 = $( '.tables table' ).dataTable
( {
    'sPaginationType': 'full_numbers',
    'bLengthChange': false,
    'aaData': [],
    'aoColumns': [{"sTitle": "Tables"}],
    'bAutoWidth': true
} );


 /*retrieve data*/
function getArr( conf_csv_path )
{
    $.ajax
    ({
        url  : 'my_url'
        success  : function( obj ) 
        {
            update_table( obj );
        }
    });
}


/* build table data */
function update_table( arr )
{        
    oTable1.fnClearTable();
    for ( input in arr )
    {
        oTable1.fnAddData( [ arr[input] );
    }                                
}

This is how I feed my table with data retrieved by ajax (not sure if this is the best practice tough, but it feels intuitive and works well):

/* initialise table */
oTable1 = $( '.tables table' ).dataTable
( {
    'sPaginationType': 'full_numbers',
    'bLengthChange': false,
    'aaData': [],
    'aoColumns': [{"sTitle": "Tables"}],
    'bAutoWidth': true
} );


 /*retrieve data*/
function getArr( conf_csv_path )
{
    $.ajax
    ({
        url  : 'my_url'
        success  : function( obj ) 
        {
            update_table( obj );
        }
    });
}


/* build table data */
function update_table( arr )
{        
    oTable1.fnClearTable();
    for ( input in arr )
    {
        oTable1.fnAddData( [ arr[input] );
    }                                
}
温暖的光 2024-12-17 11:21:39

检查fnAddData:https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文