【问题标题】:redraw datatable after ajax callajax调用后重绘数据表
【发布时间】:2016-10-16 18:51:18
【问题描述】:

我有一个带有过滤器的数据表。我每 10 秒使用一次 Ajax 来获取新数据并向表中添加新行。 (表格数据在同一页面中是动态的,不是ajax)

$(function () {
    setInterval(checkNew,1000*10);

    $( "#orderdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '2013:2050',
        dateFormat:"dd-mm-yy",
        showAnim:"fold"
    });

    var table = $('#data').DataTable({
        "lengthMenu": [[-1], ["All"]],
        "bSort": false,
        "paging":   false,
    });

    $("#status").change(function() { table.column(4).search($(this).val()).draw() });

});

function checkNew(){
    $.post('getdata.php',{max: $("#lastid").text().trim() }).done(function (data) {
        if( data.trim() !== '' ) {
            $("table#data").prepend(data.trim());
            //need to draw datatable to filter and search new data added to the table
        }
    });
}

如您所见,我正在尝试使用新数据更新或绘制表格,以便过滤或搜索它们。如果我搜索新数据,它不会显示,因为它没有加载 DOM。但我无法重绘我尝试过的表格

$("table#data").DataTable().draw(); // new rows are added but can't be searched or filtered

还有

$('table#data').dataTable().fnDraw(); //new rows are not added

那么无论如何如何编辑代码以正确绘制表格以过滤和搜索新添加的数据?

【问题讨论】:

    标签: jquery ajax datatables


    【解决方案1】:

    Datatables 将built-in functionality for handling loading data from an ajax request 提供到表中。此外,它还提供了一个reload 方法来刷新表中的数据。

    在您的情况下,您应该能够执行以下操作:

    var table = $('#data').DataTable( {
        ajax: "getdata.php"
    });
    

    然后:

    setInterval( function () {
        table.ajax.reload();
    }, 10000 );
    

    根据您的用例,您可能希望将其他选项作为参数传递给 reload 函数。我希望这会有所帮助!

    【讨论】:

    • 在 getdata.php 和获取行的 lopp 内部 $myrows[] = " ".$row['orderid']." ".$row['first_name'].' '.$row['last_name']." ".date('d-m-Y',$row['unix_time'])." ".$row[ 'final_total']." ".$row['name']." "; } 回声 json_encode($myrows);在索引中我收到此错误“无效的 json 响应”
    • [update] 在循环中:$arr[] = $row;获取整行信息,但我需要选择一些特定数据,只需 4 个字段,仍然得到相同的错误“select orders.id as orderid,orders.unix_time,orders.final_total,orders.user_id,orders.auto_cancel,users. id 为 userid、users.first_name、users.last_name、payment_methods_translation.payment_method_id、payment_methods_translation.name 来自 orders,users,payment_methods_translation where orders.id='$id' and orders.user_id = users.id and orders.payment_method_id = payment_methods_translation.payment_method_id和 orders.auto_cancel='1'"
    • [update] 我正在正确更改我的代码,但在控制台的网络选项卡中我发现这个 ajax "mydomain.com//getdata.php?_=1476648685734" 而不是 "mydomain.com// getdata.php?_=1476648685734" 这意味着 ajax url 不正确我不知道为什么它被更改了这就是为什么我得到错误(域是 https)
    • 已更新,请查看。现在我得到了 json 数据,但表格没有显示任何内容,它只是说“正在加载”
    • @PHPUser 得到答案后请不要更改您的问题。如果您有新问题,请提出新问题。
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多