You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中DataTable已获取数据但无法填充问题求助

Laravel中DataTable获取数据但无法填充的问题

问题场景

AJAX请求已成功拿到数据(console.log可正常输出),但DataTable始终显示为空。

前端JS代码

$(document).ready(function() {
    $('#time').change(function() {
        var time = $(this).val(); 
        var url = '{{ route("owner.safety.timeOverview", ":time") }}';
        url = url.replace(':time', time);

        $.ajax({
            type: 'GET',
            url: url,
            success: function(data) {

                console.log(data); // 此处能正常打印数据

                $('#overview').DataTable({
                    destroy: true, 
                    data: data, 
                    lengthMenu: [10, 25, 50, 75, 100],
                    mimeType: 'json',
                    columns: [
                        { "data": "property_id", "title": "property_id" },
                        { "data": "unit_id", "title": "unit_id" },
                        { "data": "issue_date", "title": "issue_date" },
                        { "data": "expiry_date", "title": "expiry_date" },
                        { "data": "certified_by", "title": "certified_by" },
                        { "data": "safety", "title": "safety" },
                        { "data": "reminder", "title": "reminder" }
                    ],
                    searchPane: {
                        threshold: 0
                    },
                    drawCallback: function() {
                        $(".dataTables_length select").addClass("form-select form-select-sm");
                    },
                    language: {
                        paginate: {
                            previous: '<span class="iconify" data-icon="icons8:angle-left"></span>',
                            next: '<span class="iconify" data-icon="icons8:angle-right"></span>'
                        }
                    }
                });
            }
        });
    });
});

后端PHP代码

public function getAllTime($time)
{
    if ($time == 'oneweek') {
        $difference = Carbon::now()->endOfWeek()->addWeek();
    }
    if ($time == 'onemonth') {
        $difference = Carbon::now()->addMonth()->endOfMonth();
    }
    if ($time == 'threemonth') {
        $difference = Carbon::now()->addMonths(3)->endOfMonth();
    }
    if ($time == 'sixmonth') {
        $difference = Carbon::now()->addMonths(6)->endOfMonth();
    }

    $propertyIds = Property::where('owner_user_id', auth()->id())->pluck('id')->toArray();

    $data = Safety::with(['property', 'propertyUnit'])
        ->whereIn('property_id', $propertyIds)
        ->whereBetween('expiry_date', [Carbon::now(), $difference])
        ->orderBy('id', 'DESC')
        ->get();

    return $data;
}


public function getAllDataTime($time)
{
    $overviews = $this->getAllTime($time);

    return datatables($overviews)
        ->addIndexColumn()
        ->addColumn('property_id', function ($overview) {
            return  $overview->property ? $overview->property->name : '';
        })
        ->addColumn('unit_id', function ($overview) {
            return  $overview->propertyUnit ? $overview->propertyUnit->unit_name : '';
        })
        ->addColumn('issue_date', function ($overview) {
            return  date("d-m-Y", strtotime($overview->issue_date));
        })
        ->addColumn('expiry_date', function ($overview) {
            return  date("d-m-Y", strtotime($overview->expiry_date));
        })
        ->addColumn('certified_by', function ($overview) {
            return  $overview->certified_by;
        })
        ->addColumn('safety', function ($overview) {
            return  ucfirst($overview->type);
        })
        ->addColumn('reminder', function ($overview) {
            if ($overview->expired == 1) {
                return '<div>Expired</div>';
            } else {
                $expiryDate = Carbon::parse($overview->expiry_date);
                $today = Carbon::now();
                $differenceInDays = $today->diffInDays($expiryDate);

                if ($expiryDate->isPast()) {
                    return '<div class = "over_due">Over Due</div>';
                } else {
                    $differenceInDays = $today->diffInDays($expiryDate);
                    if ($differenceInDays < 30) {
                        return '<div class = "due_soon">Due Soon</div>';
                    } else {
                        return '<div class = "not_due">Not Due</div>';
                    }
                }
            }
        })
        ->rawColumns(['reminder'])
        ->make(true);
}

问题原因与解决方法

核心问题

你用Laravel DataTables包返回的是DataTables标准格式响应(包含data、recordsTotal等顶级字段),但前端直接把整个响应对象传给了DataTable的data参数,而DataTable需要的是响应里嵌套的data数组。

解决方式1:修改前端AJAX回调

把data: data改成data: data.data,指定表格数据来源为响应中的嵌套数组:

success: function(data) {
    console.log(data);
    $('#overview').DataTable({
        destroy: true, 
        data: data.data, // 此处修改为data.data
        // 其余配置保持不变
    });
}

解决方式2:让DataTable直接处理AJAX请求

移除手动编写的$.ajax,改用DataTable内置的ajax配置,它会自动解析标准格式的响应:

$('#time').change(function() {
    var time = $(this).val(); 
    var url = '{{ route("owner.safety.timeOverview", ":time") }}';
    url = url.replace(':time', time);

    $('#overview').DataTable({
        destroy: true,
        ajax: url, // 直接传入请求地址
        lengthMenu: [10, 25, 50, 75, 100],
        columns: [
            { "data": "property_id", "title": "property_id" },
            { "data": "unit_id", "title": "unit_id" },
            { "data": "issue_date", "title": "issue_date" },
            { "data": "expiry_date", "title": "expiry_date" },
            { "data": "certified_by", "title": "certified_by" },
            { "data": "safety", "title": "safety" },
            { "data": "reminder", "title": "reminder" }
        ],
        searchPane: {
            threshold: 0
        },
        drawCallback: function() {
            $(".dataTables_length select").addClass("form-select form-select-sm");
        },
        language: {
            paginate: {
                previous: '<span class="iconify" data-icon="icons8:angle-left"></span>',
                next: '<span class="iconify" data-icon="icons8:angle-right"></span>'
            }
        }
    });
});

额外检查项

  • 确认console.log打印的响应结构,是否存在顶级data字段,且内部是表格所需的数组数据
  • 确保后端返回的字段名与前端columns配置的data属性完全匹配

内容的提问来源于stack exchange,提问作者abu abu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:03:12