【问题标题】:jQuery dynamic DataTables reloadjQuery 动态数据表重新加载
【发布时间】:2016-06-08 03:26:46
【问题描述】:

在我的 Laravel 应用程序中,我有多个页面,其中有数据表。他们都有“mydttable”类。我使用 Ajax 将数据加载到 DataTables 中。 在每个表的每一行上,我都有一个带有删除按钮的列。每当我按下 is 时,我都会在相应的行 then I want to reload the data into the datatable 上执行删除操作。我可以通过使用 if 语句询问哪个表格上有按钮来做到这一点,但我想知道是否有更简单的方法来重新加载。 更确切地说...

是我的 custom.js,我按如下方式填充数据表:

var uzTable = $('#users').DataTable( {
                "processing": true,
                "serverSide": true,
                "sAjaxSource": "sspXController?draw=1",
...
});

var cliTable = $('#clients').DataTable( {
                "processing": true,
                "serverSide": true,
                "sAjaxSource": "sspXController2?draw=1",
...
});

var marTable = $('#market').DataTable( {
                "processing": true,
                "serverSide": true,
                "sAjaxSource": "sspXController3?draw=1",
...
});

现在,删除点击事件,我在其中进行删除并希望进行重新加载

$( document ).on('click', '.ssDelete', function(e){
                e.preventDefault();
                $.ajax({
                    url:    someFormAction,
                    type:   'POST',
                    dataType: 'html',
                    success:function(data) {
                        $(".mydttable").ajax.reload();
                    }

});

我的 HTML 是这样的:

<table id="users" class="row-border hover order-column table mydttable dataTable no-footer" cellspacing="0" width="100%">
                            <thead>
                                <tr role="row">
                                   <th class="small-sorting" style="width:84px"></th>
                                   <th class="small-sorting" style="width:84px">Operatiuni</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td></td>
                                    <td></td>
                                </tr>
                            </tbody>            
                        </table>

当然,上面的HTML只是第一个DataTable(“users”)的HTML代码,其他表也有HTML代码,但我不会在这里粘贴,以免这个问题过长。 同样在任何给定时间,视图 (html) 中都会显示只有一个数据表

因此,当我单击任何具有 ssDelete ID 的按钮时,我会删除当前显示的 dataTable 的当前记录,并且我想刷新包含删除按钮的 dataTable。而且由于我没有单独为每个表执行删除功能,因此我还希望能够为 ajax 重新加载做一些更短的事情。

所以,我的目标是能够在单击“#ssDelete”按钮时重新加载文档中加载的任何 DataTable,而无需额外的分配和条件...... 而且我的尝试不起作用:

 success:function(data) {
     $(".mydttable").ajax.reload(); // NOT WORKING
 ... 

我该怎么做? 编辑 人们似乎没有阅读我的整个问题,所以我将在这里重复它的本质: 我只需要一个函数来从多个数据表中删除记录。为了做到这一点(删除部分已经完成并且已经工作)我需要能够刷新/重新加载可见数据表的内容。我需要这样做,而不必测试什么表是可见的。 基于我所有的数据表共享同一个类的事实,我应该能够调用通用数据表并将 ajax.reload() 函数应用于它。但它不起作用。我需要一种方法来访问当前 VIEW 中的任何数据表,使用一些通用的方式......比如:

$(".mydttable").ajax.reload();

$('.mydttable').dataTable().fnReloadAjax();

$('.mydttable').DataTable().ajax.reload();

显然,如果我这样做,jQuery 会尝试在常规 Table 元素上执行函数,而不是在 Table 的 dataTable 转换上执行。 如果我尝试将 DataTable() 应用于上面的元素,我会得到:

未捕获的类型错误:无法读取未定义的属性“重新加载”

到目前为止,这是我的 ajax 调用(也不起作用):

                var idtable = $('.mydttable').attr('id');
                $.ajax({
                    url:    myFormAction,
                    type:   'POST',
                    cache:  false,
                    data : { _token: csrf_token, _method:'DELETE' },
                    dataType: 'html',
                    success:function(data) {
                        $('#DeleteModalDialog').modal('hide');
                        if(idtable=='users'){
                            alert('uzerii');
                            uzTable.ajax.reload();
                        }else if(idtable=='clients'){
                            alert('Clients');
                            cliTable.ajax.reload();
                        }else if(idtable=='market'){
                            alert('Market');
                            marTable.ajax.reload();
                        }
                    }
                });

所以即使我收到警报,重新加载也不会发生,所以它知道可见表的 ID 是什么。 (uzTable、cliTable 和 marTable 是 jquery vars,如上所示)

我的代码有什么问题...?我该如何解决?

【问题讨论】:

    标签: jquery ajax datatable


    【解决方案1】:

    您需要使用服务器端处理。这是我如何做的一个例子。

    $('.dtable').DataTable({
      /*
       * Shows message dialog of loading data for slow connections
       */
      processing: true,
      /*
       * Does an ajax call to get the data
       * Happens every time you search or sort
       */
      serverSide: true,
      /*
       * full_numbers = first, last, next, previous, and numbers
       * in the pagation
       */
      pagingType: "full_numbers",
      /*l = show X entries
       * f = search box
       * <> = div
       * <"class" = class name
       * t = table
       * r = 'proccessing' dialog
       * i = 10 out of 1000 records
       * p = pagation
       * */
      dom: 'lf<"nstuff"p><"toolbar">trip',
      /*
       * Defines the ajax call
       */
      ajax: {
        url: 'url.php',
        datatype: "json",
        type: "post",
        /*Adds data to ajax call*/
        data: function(d) {
          d.action = 'list';
        }
      },
      /*Defines columns*/
      columns: [
        /* Everything in here is sent to server upon ajax call.
         * Orderable false = no arrows to order by
         * searchable false = doesn't search that column
         * */
        {
          title: "name",
          render: function() {
            /*
             * arguments[2] is the third parameter passed in through the
             * function. it holds the entire row data in it.
             */
            var row = arguments[2];
            return "<a href='?" + row.id + "'>" + row.name + "</a>";
          }
        }, {
          title: "Info",
          "orderable": false,
          render: function() {
            return arguments[2].email;
          }
        }, {
          title: "Action",
          data: 'id',
          "orderable": false
        }
      ],
      /*Orders from this to that*/
      order: [
        [0, 'asc']
      ]
    });
    <?php
    function list($REQUEST) {
            /*
             * Draw is returned back to datatables in order for javascript to not render
             * Older draws first in case of async ajax calls.
             */
            $draw = $this->aspam($REQUEST, true, 'draw');
            /* Query Handles the search field in the datatables plugin */
            $query = $this->aspam($this->aspam($REQUEST, false, 'search'), false, 'value');
            /* Data holds the extra variables */
            $data = $this->aspam($REQUEST, false, 'data');
            /* This is the array of order from datatables */
            $order = $this->aspam($REQUEST, false, 'order');
            /* Where to start the limit */
            $start = $this->aspam($REQUEST, true, 'start');
            /* how long the limit is */
            $length = $this->aspam($REQUEST, true, 'length');
            /* Set up all the variables defaults to not throw errors */
            $orderby = '';
            $where = '';
            $first = TRUE;
            /* if order is array itterate through it and set the order */
            if (is_array($order)) {
                foreach ($order as $o) {
                    if ($first) {
                        $first = FALSE;
                    } else {
                        $orderby .= ',';
                    }
                    /* 0 = Name
                     * $o[dir] is either asc or desc based on datatables
                     */
                    switch ($o['column']) {
                        case 0:
                        case '0':
                            $orderby .= "entity_name $o[dir]";
                            break;
                    }
                }
                /* if not empty create the order by */
                if (!empty($orderby)) {
                    $orderby = "ORDER BY $orderby";
                }
            }
            /* if the search string is not empty search all the searchable fields */
            if (!empty($query)) {
                $where .= "
                    AND (
                        name like '%$query%'
                    )";
            }
    
            /* This is the selection query 
             * It creates the sql with out and with the where
             */
    
            $sql_nowhere = ($sql = "
                select from where
            ");
            $sql_somewhere = ($sql .= "
                    $where
            ");
            $sql .= "
                    $orderby
                    LIMIT $start,$length
            ";
            /*
             * after all the where and join clauses are created get the filtered
             * count of all the records
             */
            $recordsFiltered = $this->getCounts($sql_somewhere);
            /* The total amount of records in this call */
            $recordsTotal = $this->getCounts($sql_nowhere);
            if (!$temp = $this->retrieve($sql)) {
                /* if no results are shown create $temp as an empty array to not through errors */
                $temp = [];
            }
            /* creates the datatables array that it likes so it won't through an error */
            $array = array(
                'draw' => $draw
                , 'recordsTotal' => $recordsTotal
                , 'recordsFiltered' => $recordsFiltered
                , 'data' => $temp
            );
            return $array;
        }
    
        /**
         * gets the total count of sql
         * @param type $sql
         * @return type
         */
        function getCounts($sql) {
            return $this->retrieve("SELECT count(*) as count FROM ($sql) as z")[0]['count'];
        }

    除此之外,我建议使用按钮上的点击事件来触发删除。

    $('button').click(function() {
      var id = $(this).data('id');
      deleteMe(id).done(function() {
        $('dtable').reload();
      });
    });
    
    function deleteMe(id) {
      /*code for what ever you do with the id.*/
      return $.ajax();
    }
    <button data-id="555">
      Me
    </button>

    此脚本不会帮助您即兴发挥,但它会为您指明正确的方向。

    编辑

    var tables = [];
    var options = [{
      ajax: 1
    }, {
      ajax: 2
    }, {
      ajax: 3
    }, {
      ajax: 4
    }, ];
    $('dtable').each(function(index) {
      $(this).data('id', index);
      tables.push($(this).DataTables(options[index]));
    });
    $(document).on('click', '.ssDelete', function(e) {
      var index = $(this).closest('dtable').data('id');
      e.preventDefault();
      $.ajax({
        url: someFormAction,
        type: 'POST',
        dataType: 'html',
        success: function(data) {
          tables[index].ajax.reload();
        }
      });
    });
    <table class='dtable'></table>
    <table class='dtable'></table>
    <table class='dtable'></table>
    <table class='dtable'></table>

    每次执行数据表时,它都会返回数据表句柄。您需要使用该句柄来刷新表格。我提出了一种无需大量冗余代码即可一次添加多个表的方法。只要确保您的options.lengthdtable.length 相同。否则,您将通过并索引超出范围。

    【讨论】:

    • 感谢您的广泛回答,但您错过了我的实际问题。我已经为 Ajax 使用服务器端处理并为我的 dataTable 获取数据。我的问题是我的项目中至少有 5 个数据表(全部加载了服务器端处理 ajax),我想对我的所有数据表使用相同的删除 jquery 函数。所以我需要能够以某种方式(按类)解决它们,而不是检查 IF-ELSE-IF。那是我的问题。
    • 您可以通过抓取某种类型的 DOM 元素来遍历按下了哪个按钮。在事件中,您可以获得$(this) 元素并遍历您需要的功能。
    • 好的。因此,正如您在问题中看到的那样,我正在这样做。但它不是那样工作的。可能是因为我得到的是一个 TABLE 元素,而不是一个 DATATABLE 元素。所以我似乎无法抓取一个 Table 元素并将其应用于 ajax.reload()。它只是不能那样工作。请自己尝试一下,这样您就可以理解我在说什么。您似乎已经拥有了大部分类似的项目。只需尝试使用带有 Table-DataTable 元素的 2 个 HTML,使用相同的 custom.js 文件,在其中放置一个处理两个数据表的删除函数。我不知道如何更好地解释
    • 对,忘了处理程序。当您使用数据表时,它会返回您用来刷新表的处理程序。
    • 没错。所以我需要一种方法来访问可见表的处理程序并告诉它重新加载页面。知道怎么做吗?查看我的问题的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2018-10-24
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    相关资源
    最近更新 更多