jQuery 动态数据表重新加载

标签 jquery ajax datatable

在我的 Laravel 应用程序中,我有多个页面,其中有数据表。他们都有“mydttable”类。我使用 Ajax 将数据加载到 DataTables 中。 在每个表的每一行上,我有一列带有删除按钮。每当我按下 is 时,我都会在相应的行上执行删除,然后我想将数据重新加载到数据表中。我可以通过使用 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(“用户”)的 HTML,其他表也有 HTML 代码,但我不会将其粘贴到此处,以避免使这个问题过长。 此外,在任何给定时间, View (html) 中都会显示只有一个数据表

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

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

 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() 应用于上面的元素,我将得到:

Uncaught TypeError: Cannot read property 'reload' of undefined

这是到目前为止我的 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 变量,如上所示)

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

最佳答案

您将需要使用服务器端处理。这是我如何做到这一点的示例。

$('.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 相同即可。否则,您将通过索引并超出范围。

关于jQuery 动态数据表重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625882/

相关文章:

javascript - 对预检请求的响应未通过访问控制检查

使用 HttpsUrlConnection 的 Java POST 连接超时

c# - 如何在aspx中创建一个json数组

c# - 如何将 `linq` 的结果返回到 DataTable?

javascript - 在 IFrame 中运行 Skrollr

php - 如何将 JavaScript 代码传递给 Yii 框架方法?

jquery - 选择数据源等于 all 的 .button

r - 如何使用隐藏列对 DataTable 进行排序

jquery - 全屏视频作为网站标题背景

javascript - 为什么没有在页面源中添加元素