【问题标题】:How to Export Data with custom button in Data Table如何使用数据表中的自定义按钮导出数据
【发布时间】:2018-06-01 05:43:09
【问题描述】:

我是 Jquery 的新手,我正在创建一个自定义按钮,以仅选定行的 csv 格式从 db 导出数据,问题是我不知道如何获取数据的 ID,因此基于选定的ID,我可以对 PHP 脚本进行 ajax 调用以导出选定的记录。我该怎么做?

我的数据表截图是,

代码是,

    $('.dataTables-example').DataTable({

        pageLength: 25,
        "order": [[0, "desc"]],
        "stateSave": true,
        responsive: true,
        dom: '<"html5buttons"B>lTfgitp',
        buttons: [
            'selectAll',
            'selectNone',
            {
                text: 'Export Selected Rows',
                action: function ( e, dt, node, config ) {

                    console.log(dt.row());

                }, exportOptions: {
                    modifier: {
                        selected: true
                    }
                }
            }
        ],
        select: true,

    });

目前我的代码的结果是,

【问题讨论】:

  • 我的建议是永远不要显示从数据库到表的 id。而是使用增量运算符。
  • 那么如何识别行呢?
  • 使用$(this)

标签: javascript php jquery datatable datatables


【解决方案1】:

假设id是每行第一个单元格的文本,点击按钮,按类搜索选定的行(如果你使用DataTables select插件,选定的行将有@987654324 @类):

function onButtonClick() {
   var id = $('#myTable')                 
              .find('tbody')
              .find('tr.selected')
              .find('td')
              .eq(0) // Get first cell
              .text() // Get the text of cell
              .trim(); // Trim the text

   // Call your method providing the id
}

我建议初始化 DataTable 插件,提供如下数据:

HTML

<table id="myTable"></table>

jQuery

// Your data
var data = [
   { ID: 0, ... },
   { ID: 1, ... },
   { ID: 2, ... },
   ....
];

// Initialize the plugin
$('#myTable').DataTable({
   dom: '...',
   data: data,
   columns: [
     {
       data: 'ID',
       title: 'ID'
     },
     ...
   ],
   buttons: [...]
});

然后,在单击按钮时,您可以像这样检索所选行的数据:

var rowData = $('#myTable').DataTable().rows('.selected').data();

rowData 是一个类似数组的对象,包含所选行的数据

您可以查看documentation

【讨论】:

  • 非常感谢您的回复,但是如何访问该数组?
  • 获得 rowData 对象后,只需获取 id,例如第一行:rowData[0].ID
【解决方案2】:

您可以在导出按钮单击中执行以下替代操作。它使用 jquery 每个函数获取所选 tr(具有 selected 类)的所有 id。

var data = {
  'selected_ids': []
};

$('tbody tr.selected').each(function() {
  data['selected_ids'][data['selected_ids'].length] = $(this).find('td:eq(0)').html();
});
console.log(data); // var data holds the selected ids. You can pass it in your ajax data as it is.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多