Jquery 使用 ajax 填充数据时 DataTable 排序不起作用

Jquery DataTable sorting not working when using ajax to populate data

我一直在尝试使用 ajax 在页面加载时填充 table 中的数据。数据在我的 table 中加载正常,但我面临的问题是 jQuery 的排序和分页。当我单击它的排序箭头时,它显示 table 中没有可用数据。我的 table 代码是:

{{-- /Table Starts form here --}}
<table id="DtAdminAttendance" class="table table-striped custom-table mb-0 datatable">
    <thead>
        <tr>
            {{-- <th style="display: none">tbl_index</th> --}}
            <th>Emp ID - Name</th>
            <th>Date </th>
            <th>Punch In</th>
            <th>Punch Out</th>
            <th>Worked Hours</th>
            <th>Status</th>
            <th class="text-right">Action</th>
        </tr>
    </thead>
    
    <tbody id="atn-tbody">
        {{-- table data goes here --}}
    </tbody>
</table>

我的 ajax 对于这个 table 是:

<script>
    //for displaying table data department
    $(document).ready(function () {
        // var table = $('#DtAdminAttendance').DataTable();
        $.ajax({
            type: "GET",
            url: "fetch-Attendance",
            dataType: "json",
            success: function (response) {
                $('tbody').html("");
                $.each(response.Attendance_list, function (key, employee) {
                    if (employee.status == "Absent") 
                    {
                        $('tbody').append(
                            `<tr>\
                                <td style="display: none"> ${employee.id} </td>\
                                <td> ${employee.employeeID} - ${employee.name} </td>\
                                <td> ${employee.date} </td>\
                                <td> ${employee.Punch_in} </td>\
                                <td> ${(employee.Punch_Out == null ? '-' : employee.Punch_Out)} </td>\
                                <td> ${employee.totalhours} </td>\
                                <td class="badge  badge-danger"> ${employee.status} </td>\

                                <td class="text-right">
                                    <div class="dropdown dropdown-action">
                                        <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <i class="material-icons">more_vert</i>
                                        </a>

                                        <div class="dropdown-menu dropdown-menu-right">
                                            <button type="button" class="dropdown-item edtAtn" href="#" data-toggle="modal" data-target="#edit_Attendance" value="  ${employee.id}">
                                                <i class="fa fa-pencil m-r-5"></i> Edit
                                            </button>

                                            <button type="button" class="dropdown-item dltAtn" href="#" data-toggle="modal" data-target="#delete_Attendance" value="${employee.id}">
                                                <i class="fa fa-trash-o m-r-5"></i> Delete
                                            </button>
                                        </div>
                                    </div>\
                                </td>\
                            </tr>`);
                    }
                    else if (employee.status == "Present") 
                    {
                        $('tbody').append(
                            `<tr>\
                                <td style="display: none"> ${employee.id} </td>\
                                <td> ${employee.employeeID} '-' {employee.name}</td>\
                                <td> ${employee.date}</td>\
                                <td> ${employee.Punch_in}</td>\
                                <td> ${(employee.Punch_Out == null ? '-' : employee.Punch_Out)}</td>\
                                <td> ${employee.totalhours}</td>\
                                <td class="badge  badge-success"> ${employee.status}</td>

                                <td class="text-right">
                                    <div class="dropdown dropdown-action">
                                        <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <i class="material-icons">more_vert</i>
                                        </a>

                                        <div class="dropdown-menu dropdown-menu-right">
                                            <button type="button" class="dropdown-item edtAtn" href="#" data-toggle="modal" data-target="#edit_Attendance" value="${employee.id}" >
                                                <i class="fa fa-pencil m-r-5"></i> Edit
                                            </button>

                                            <button type="button" class="dropdown-item dltAtn" href="#" data-toggle="modal" data-target="#delete_Attendance" value="${employee.id}">
                                                <i class="fa fa-trash-o m-r-5"></i> Delete
                                            </button>
                                        </div>
                                    </div>\
                                </td>\
                            </tr>`);
                    }
                    else if (employee.status == "Late") 
                    {
                        $('tbody').append(
                            `<tr>\
                                <td style="display: none"> ${employee.id} </td>\
                                <td> ${employee.employeeID} '-' ${employee.name} </td>\
                                <td> ${employee.date}</td>\
                                <td> ${employee.Punch_in}</td>\
                                <td> ${(employee.Punch_Out == null ? '-' : employee.Punch_Out)}</td>\
                                <td> ${employee.totalhours}</td>\
                                <td class="badge  badge-warning"> ${employee.status} </td>

                                <td class="text-right">
                                    <div class="dropdown dropdown-action">
                                        <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <i class="material-icons">more_vert</i>
                                        </a>

                                        <div class="dropdown-menu dropdown-menu-right">
                                            <button type="button" class="dropdown-item edtAtn" href="#" data-toggle="modal" data-target="#edit_Attendance" value="${employee.id}">
                                                <i class="fa fa-pencil m-r-5"></i> Edit
                                            </button>

                                            <button type="button" class="dropdown-item dltAtn" href="#" data-toggle="modal" data-target="#delete_Attendance" value="${employee.id}">
                                                <i class="fa fa-trash-o m-r-5"></i> Delete
                                            </button>
                                        </div>
                                    </div>\
                                </td>\
                            </tr>`);
                    } 
                    else if (employee.status == "Unpaid Halfday") 
                    {
                        $('tbody').append(
                            `<tr>\
                                <td style="display: none"> ${employee.id} </td>\
                                <td> ${employee.employeeID} '-' ${employee.name} </td>\
                                <td> ${employee.date}</td>\
                                <td> ${employee.Punch_in}</td>\
                                <td> ${(employee.Punch_Out == null ? '-' : employee.Punch_Out)} </td>\
                                <td> ${employee.totalhours}</td>\
                                <td class="badge  badge-info"> ${employee.status} </td>

                                <td class="text-right">
                                    <div class="dropdown dropdown-action">
                                        <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <i class="material-icons">more_vert</i>
                                        </a>

                                        <div class="dropdown-menu dropdown-menu-right">

                                        <button type="button" class="dropdown-item edtAtn" href="#" data-toggle="modal" data-target="#edit_Attendance" value="${employee.id}">
                                            <i class="fa fa-pencil m-r-5"></i> Edit
                                        </button>

                                        <button type="button" class="dropdown-item dltAtn" href="#" data-toggle="modal" data-target="#delete_Attendance" value="${employee.id}" >
                                            <i class="fa fa-trash-o m-r-5"></i> Delete
                                        </button>
                                    </div></div>
                                </td>
                            </tr>`);
                    }
                });
                $('#DtAdminAttendance').DataTable();
            }
        });
    });
</script>

现在,当我转到页面时,它会加载 table 行:

但是当我使用任何列进行排序时,它显示 table:

中没有可用数据

添加jQuery(script) and dataTable (script, style)对HTML文件的引用后,应该在脚本中添加如下代码对 dataTable 进行排序。为了使项目正常工作,您应该添加脚本 运行 最后一个文件。据我评论,应用 dataTable 样式没有问题。您可能没有将 dataTable 脚本引用 添加到项目中。使用下面模板中的引用和 <script> 元素中的命令重新测试项目。

<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
</head>

<body>
    <table id="DtAdminAttendance" class="display" style="width:100%">
        <!-- Something -->
    </table>

    <script>
        $(document).ready(function () {
            $('#DtAdminAttendance').DataTable({
                order: [
                    [3, 'desc'],
                    [0, 'asc']
                ]
            });
        });
    </script>
</body>
</html>

根据我的测试,您的问题不可重现。它在我这边很好用。

JS Fiddle: OP's test code

尽管如此,您的源代码可以进行一些改进,这可能会解决您的问题。

不是手动操作 HTML table,而是使用数据表 API 自动生成 table。

JS Fiddle: Improved source code

HTML

<table id="DtAdminAttendance" class="table table-striped custom-table mb-0 datatable">
    <thead>
        <tr>
            <th>tbl_index</th>
            <th>Emp ID - Name</th>
            <th>Date</th>
            <th>Punch In</th>
            <th>Punch Out</th>
            <th>Worked Hours</th>
            <th>Status</th>
            <th class="text-right">Action</th>
        </tr>
    </thead>
    <tbody id="atn-tbody">
    </tbody>
</table>

JavaScript

根据需要更改ajax: {url: '...'}。即:'/fetch-Attendance'.

$(document).ready(function () {
    $("#DtAdminAttendance").DataTable({
        scrollX: true,
        autoWidth: false,
        ajax: {
            type: "GET",
            url: "https://run.mocky.io/v3/9ef15223-a192-4f3c-a2fb-843048cb31dc",
            dataType: "JSON",
            dataSrc: "Attendance_list",
            async: true,
        },
        columns: [
            {data: "id"},
            {
                data: "name", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html(`${oData.employeeID + "-" + oData.name}`);
                }
            },
            {data: "date"},
            {data: "Punch_in"},
            {data: "Punch_Out"},
            {data: "totalhours"},
            {
                data: "status", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    const statusBtn = $("<span class='badge'></span>");
                    let badgeColor = "badge-secondary";

                    switch (oData.status) {
                        case "Absent":
                            badgeColor = "badge-danger";
                            break;
                        case "Present":
                            badgeColor = "badge-success";
                            break;
                        case "Late":
                            badgeColor = "badge-warning";
                            break;
                        case "Unpaid Halfday":
                            badgeColor = "badge-info";
                            break;

                    }

                    statusBtn.addClass(badgeColor);
                    statusBtn.text(oData.status);

                    $(nTd).html(statusBtn.get(0));
                }
            },
            {
                data: null, "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    const actionBtn = $(`
                    <div class="d-inline-block text-right">
                        <div class="dropdown dropdown-action">
                            <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                <i class="material-icons">more_vert</i>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <button style="cursor: pointer;" type="button" class="dropdown-item edtAtn" data-toggle="modal" data-target="#edit_Attendance" value="${oData.id}">
                                    <i class="fa fa-pencil m-r-5"></i>
                                    Edit
                                </button>
                                <button style="cursor: pointer;" type="button" class="dropdown-item dltAtn" data-toggle="modal" data-target="#delete_Attendance" value="${oData.id}">
                                    <i class="fa fa-trash-o m-r-5"></i>
                                    Delete
                                </button>
                            </div>
                        </div>
                    </div>
                `);

                    $(nTd).html(actionBtn.get(0));
                },
                orderable: false,
                searchable: false
            }
        ],
        columnDefs: [
            {
                "targets": [0],
                "visible": false
            },
            {
                "defaultContent": "-",
                "targets": "_all"
            }

        ]
    });

});