如何使用数据表中的自定义按钮导出数据

时间:2018-06-01 05:43:10

标签: javascript php jquery datatable datatables

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

我的数据表截图是, enter image description here

代码是,

    $('.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,

    });

目前我的代码的结果是, enter image description here

2 个答案:

答案 0 :(得分:0)

假设id是每行的fisrt单元格的文本,在按钮单击时,按类搜索所选行(如果使用DataTables select插件,则所选行将拥有selected类:

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

答案 1 :(得分:0)

您可以在导出按钮单击中执行以下选项。它使用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.
相关问题