【问题标题】:AJAX + jQuery + Datatables plugin - add custom column to requested ajax data?AJAX + jQuery + Datatables 插件 - 向请求的 ajax 数据添加自定义列?
【发布时间】:2017-04-22 12:34:47
【问题描述】:

我正在通过 AJAX / PHP 将数据拉入表中,并希望通过 DataTable JS 插件显示数据。数据查询运行良好,但现在我想为每条记录添加一列,其中包含几个按钮,允许用户预览/编辑/删除相应的记录。

我似乎无法将包含按钮的 html 代码的附加列数据附加到数据表数组,DataTable 分别抛出一条错误消息,指出接收到的 json 数据格式不正确。这必须是指按钮的html代码,因为它在没有额外列的情况下提取数据时可以正常工作。

在我的代码下面:

Mysqli 查询:

$result = $db->query($sql) or die(mysqli_error($db));       

if($result->num_rows > 0) {
    // return total number of rows for pagination
    $totalData = $result->num_rows;
    $totalFiltered = $totalData;

    // return table data - MUST BE NON-ASSOCIATIVE ARRAY
    while($row = mysqli_fetch_array($result)) {
        $data[] = array(
            $row['ID'],
            $row['Holidex'],
            $row['First'],
            $row['Last'],
            $row['Email'],
            "Button" => "<button type=\"button\" class=\"btn btn-primary btn-xs\" data-toggle=\"modal\" data-target=\"#EditEmailModal\" data-keyboard=\"true\" data-id=\"".$row['ID']."\"><i class=\"fa fa-edit\"></i></button> <button type=\"button\" class=\"btn btn-danger btn-xs\" data-toggle=\"modal\" data-target=\"#EditEmailModal\" data-keyboard=\"true\" data-id=\"".$row['ID']."\"><i class=\"fa fa-times\"></i></button>",
        );
    }

    // finalize array with elements required by DataTable plugin
    $json_data = array(
      "recordsTotal"    => intval( $totalData ),        // total number of records
      "recordsFiltered" => intval( $totalFiltered ),    // total number of records after searching, if there is no searching then totalFiltered = totalData
      "success"         => true,                        // must have a success message (false / true)
      "aaData"          => $data                        // table data as array
    );

    echo json_encode($json_data);
}

我尝试用单引号 ' 替换双引号 " 并删除转义反斜杠 \ 但没有成功。我还能做什么?

谢谢, A2k

更新: 相应地更新了我的 JS 以在服务器端过程完成后生成按钮,但我无法将 data.ID 值附加到按钮 data-* 元素。我在引用 ID 列时尝试同时使用dataaaData,为什么它没有获取值?

更新2: 编辑了 JS 代码以反映最新的变化

<script type="text/javascript" language="javascript" class="init">                  
    $(document).ready(function() {
        $('#auto_cc_table').DataTable( {
            // load table data via AJAX
            "processing": true,
            "serverSide": true,
            "ajax":{
                url: "../../plugins/MySQL/ajax_action.php", // json datasource
                data: { action:"view_auto_cc_email_AJAX" },
                type: "post",  // connection method (default: GET)
            },
            "columns": [
                { "aaData": "ID" },
                { "aaData": "Holidex" },
                { "aaData": "First" },
                { "aaData": "Last" },
                { "aaData": "Email" },
                { "aaData": null },
            ],
            columnDefs: [{
                className: "text-right", "targets": [1],
                className: "text-nowrap", "targets": [3],

                // puts a button in the last column
                targets: [-1], render: function (a, b, data, d) {

                //console.log(data);        // error - undefinded in console
                console.log(row);           // ok
                console.log(row.ID);        // error - undefined in console
                //console.log(row.Holidex); // error - undefined in console
                //console.log(row.First);       // error - undefined in console
                //console.log(row.Last);        // error - undefined in console
                //console.log(row.Email);       // error - undefined in console

                    return '<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#EditEmailModal" data-keyboard="true" data-id="'+ data.ID +'"><i class="fa fa-edit"></i></button> '
                    +'<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#EditEmailModal" data-keyboard="true" data-id="'+ data.ID +'"><i class="fa fa-times"></i></button>'
                },
            }],
            dom: 'Bfrtip',
            stateSave: true,
            buttons: [
              'copyHtml5',
              'excelHtml5',
              'csvHtml5',
              'pdfHtml5',
              {
                extend: 'print',
                message: '(c) Copyright'
              },
              {
              extend: 'collection',
              text: 'Others',
              buttons: [
                {
                  text: 'Toggle button',
                  action: function ( e, dt, node, config ) {
                  dt.column( -6 ).visible( ! dt.column( -6 ).visible() );
                  }
                },
                'colvis',
                'columnsToggle',
              ]
              },
            ],
            "pagingType": "full_numbers",
            "pageLength": 25,
            "lengthChange": true,
            "searching": true,
            "ordering": false,
            "order": [[ 1, "asc" ], [ 2, "asc" ]],
            "info": true,
            "autoWidth": true
        })
    });
</script>

更新 3: 按照下面的解决方案,我更新了上面的 JS 代码以缩小控制台日志问题,了解到 console.log(data)console.log(row.ID) 在 JS 控制台中导致 undefined,而 console.log(row) 返回完整的行数据,例如。 7,ADMIN,John, Doe,john.doe@gmail.com.

由于我无法通过row.ID 获得特定行的ID,我现在正在使用.split() 来获得第一个左逗号分隔值,但这只不过是一个不应该的东西的猴子补丁排在第一位……

注意:var rowData = $('#auto_cc_table').DataTable().rows(btnRow).data()[0]; 确实会返回如上所示的完整行数据。

模态调用:

// DISPLAY EMAIL RECORD
$('#EditEmailModal').on('show.bs.modal', function (event) {

      var button = $(event.relatedTarget);
      var btnRow = button.closest("tr");
      var rowData = $('#auto_cc_table').DataTable().rows(btnRow).data()[0];
      var rowData1 = rowData + '';
      var rowData2 = rowData1.split(",");

      alert("RowData: " + rowData2);
});

【问题讨论】:

  • 您为什么要尝试将按钮添加到您的数据集中?您应该通过 columnDefs 渲染选项添加它

标签: php jquery ajax datatables


【解决方案1】:

您要做的是在服务器端创建按钮并将它们作为 ajax 的一部分发送。您应该做的是将按钮创建为 DataTable 定义的一部分。看起来像这样:

这里没有使用 data-id,而是使用一个事件处理程序,可以让您获取整行的数据。 http://jsbin.com/viqafe/edit?html,js,output 修改为这样做。

// button click event handler

$('#EditEmailModal').on('show.bs.modal',function (event) {
    var button = $(event.relatedTarget);
    var btnRow = button.closest("tr");
    var rowData = $('#example').DataTable().rows(btnRow).data()[0];

     // process the data here
 });


            var table = $('#yourTable').DataTable({
                "data": yourDataObject,
                // because your data is in arrays, not objects the column defs have to be changed
                "columns": [
                { "name": "ID" },
                { "name": "Holidex" },
                { "name": "First" },
                { "name": "Last" },
                { "name": "Email" },
                { "name": "Buttons"},
                ],
                columnDefs: [{
                    // puts a button in the last column
                    targets: [-1], render: function (data, type, row, meta) {

                       // your id is in the first cell if the inner array so
                           var ID = row[0];

                            // look at your console and make sure there is a value here.
                            console.log(ID);

                           console.log(row);


                            return '<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#EditEmailModal" data-keyboard="true" data-id="' + ID +'"><i class="fa fa-edit"></i></button>' 
                                   +'<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#EditEmailModal" data-keyboard="true" data-id="' + ID +'"><i class="fa fa-times"></i></button>'
                    }
                }],

            });

        });

【讨论】:

  • 谢谢。代码似乎可以正常工作,但我无法将 data.ID 值附加到按钮。有没有机会帮忙看看?谢谢
  • ID 基于您上面的列定义。我添加了一些 console.logs,因此您可以检查日志以确保 ID 是有效的数据对象名称。区分大小写
  • 'ID' 是正确的,这是整个代码中使用的实际列名和语法...... Chrome 调试器认为按钮 HTML 未定义。
  • 我在 chrome 中运行了 jsbin.com/viqafe/edit?html,js,output 的底部逻辑。按钮按预期显示
  • 您可以按原样保留数据,只需按位置而不是名称来寻址。我更新了上面的逻辑以反映这一点。
猜你喜欢
  • 2011-12-02
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多