jQuery动态DataTables重新加载

时间:2016-02-25 11:23:00

标签: jquery ajax datatable

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

是我的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(“用户”)的HTML,其他表也有HTML代码,但我不会在这里粘贴它以避免使这个问题过长。 此外,在任何给定时间,视图(html)中都会显示仅一个dataTable

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

因此,我的目标是能够在单击“#ssDelete”按钮时重新加载文档中加载的任何DataTable,而无需额外的重新标记和条件... 我的尝试无效:

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

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

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

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

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

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

  

未捕获的TypeError:无法读取未定义的属性'reload'

到目前为止,这是我的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)

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

1 个答案:

答案 0 :(得分:2)

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

$('.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相同即可。否则你将通过并索引越界。