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

如何在Laravel控制器的overview_result方法中接收AJAX多参数

问题描述

我尝试使用AJAX传递多个参数,结合DataTables实现请求,以下是我的JavaScript、Laravel路由及控制器代码,请问如何在overview_result函数中接收这些多个参数?

JavaScript代码

$('.overview_value').change(function() {    
    $('#overview').DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        pageLength: 100,
        responsive: true,
        ajax: baseUrl+'/owner/safety/overview_result/'+$("#time").val()+'/'+$("#property_id").val()+'/'+$("#unit_id").val()+'/'+$("#status").val(),
        order: [1, 'desc'],
        ordering: false,
        autoWidth: false,
        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>'
            }
        },
        columns: [
            { "data": "property_id" },
            { "data": "unit_id" },
            { "data": "issue_date" },
            { "data": "expiry_date" },
            { "data": "certified_by" },
            { "data": "safety" },
            { "data": "reminder" },
        ]
    });
});

Laravel路由代码

Route::get('overview_result/{time}/{property}/{unit}/{status}', [OverviewController::class, 'overview_result'])->name('overview_result');

Laravel控制器代码

public function overview_result( $time, $property, $unit, $status )
{
    if ($time == 'all') {
        $difference = Carbon::now()->addYears(100);
    }
    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();
    }

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

    return $data;
}

解决方案

你的代码已经实现了参数接收,但存在参数不能为空、代码冗余、未使用status参数等问题,以下是优化后的实现方案:

方案一:使用查询参数(推荐,更灵活)

这种方式不需要在URL路径里拼接参数,而是通过DataTables的data选项传递键值对,适配多可选参数场景。

1. 修改路由

去掉路径参数,改为接收GET查询参数:

Route::get('overview_result', [OverviewController::class, 'overview_result'])->name('overview_result');

2. 优化控制器

通过request()获取参数,添加非空判断,优化时间逻辑:

use Carbon\Carbon;

public function overview_result()
{
    // 获取参数,设置默认值
    $time = request()->get('time', 'all');
    $property = request()->get('property');
    $unit = request()->get('unit');
    $status = request()->get('status');

    // 用数组映射替代多个if,更简洁
    $timeMap = [
        'all' => Carbon::now()->addYears(100),
        'oneweek' => Carbon::now()->endOfWeek()->addWeek(),
        'onemonth' => Carbon::now()->addMonth()->endOfMonth(),
        'threemonth' => Carbon::now()->addMonths(3)->endOfMonth(),
        'sixmonth' => Carbon::now()->addMonths(6)->endOfMonth(),
    ];
    // 兜底默认选择all
    $difference = $timeMap[$time] ?? $timeMap['all'];

    // 构建查询
    $query = Safety::with(['property', 'propertyUnit'])
        ->whereBetween('expiry_date', [Carbon::now(), $difference]);

    // 非空才添加条件,避免空值筛选
    if ($property) {
        $query->where('property_id', $property);
    }
    if ($unit) {
        $query->where('unit_id', $unit);
    }
    // 补上原代码遗漏的status筛选
    if ($status) {
        $query->where('status', $status);
    }

    $data = $query->orderBy('id', 'DESC')->get();

    return $data;
}

3. 修改JavaScript的AJAX配置

改用DataTables的ajax对象写法,传递查询参数:

$('.overview_value').change(function() {    
    $('#overview').DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        pageLength: 100,
        responsive: true,
        // 修改ajax配置为对象形式
        ajax: {
            url: baseUrl + '/owner/safety/overview_result',
            type: 'GET',
            data: {
                time: $("#time").val() || 'all', // 为空时用默认值all
                property: $("#property_id").val(),
                unit: $("#unit_id").val(),
                status: $("#status").val()
            }
        },
        order: [1, 'desc'],
        ordering: false,
        autoWidth: false,
        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>'
            }
        },
        columns: [
            { "data": "property_id" },
            { "data": "unit_id" },
            { "data": "issue_date" },
            { "data": "expiry_date" },
            { "data": "certified_by" },
            { "data": "safety" },
            { "data": "reminder" },
        ]
    });
});

方案二:保持路径参数(处理可选场景)

如果坚持用路径参数,需要修改路由允许参数为空,并在控制器设置默认值:

1. 修改路由

给参数添加?标记为可选:

Route::get('overview_result/{time?}/{property?}/{unit?}/{status?}', [OverviewController::class, 'overview_result'])->name('overview_result');

2. 控制器设置默认值

public function overview_result($time = 'all', $property = null, $unit = null, $status = null)
{
    // 时间逻辑同方案一的数组映射
    $timeMap = [
        'all' => Carbon::now()->addYears(100),
        'oneweek' => Carbon::now()->endOfWeek()->addWeek(),
        'onemonth' => Carbon::now()->addMonth()->endOfMonth(),
        'threemonth' => Carbon::now()->addMonths(3)->endOfMonth(),
        'sixmonth' => Carbon::now()->addMonths(6)->endOfMonth(),
    ];
    $difference = $timeMap[$time] ?? $timeMap['all'];

    $query = Safety::with(['property', 'propertyUnit'])
        ->whereBetween('expiry_date', [Carbon::now(), $difference]);

    if ($property) {
        $query->where('property_id', $property);
    }
    if ($unit) {
        $query->where('unit_id', $unit);
    }
    if ($status) {
        $query->where('status', $status);
    }

    $data = $query->orderBy('id', 'DESC')->get();

    return $data;
}

3. JavaScript处理空值

拼接URL时为空参数填充默认值,避免URL出现空段:

let time = $("#time").val() || 'all';
let property = $("#property_id").val() || '';
let unit = $("#unit_id").val() || '';
let status = $("#status").val() || '';

$('#overview').DataTable({
    // ...其他配置
    ajax: `${baseUrl}/owner/safety/overview_result/${time}/${property}/${unit}/${status}`,
    // ...其他配置
});

内容的提问来源于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 05:44:54