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

Laravel中使用Ajax无法将Week输入值传递到控制器方法

问题:Ajax请求后Laravel控制器无法获取Week输入值?

我用Chart.js展示卡路里追踪周度柱状图,最初用表单提交Week输入值到控制器时,路由加载完成后图表会消失。改用Ajax请求避免图表消失后,控制器却无法获取到Week输入的值。

相关代码

HTML输入框:

<input type="week" class="week-picker" id="week_input" name="week_input" onchange="SubmitForm(event);" />

Ajax代码:

function SubmitForm(event) {
    // Prevent form from being submitted normally
    event.preventDefault();

    // Send AJAX request to server to fetch chart data
    $.ajax({
        type: 'GET',
        url: '/calorie_tracker_weekly',
        data: $('#calorieBarChartWeekly').serialize(),
        success: function(data) {
            ShowChart(data);
        }
    });
}

控制器方法:

public function calorieTrackerWeekly(Request $request)
{
   $date = $request->input('week_input');
   // Rest of the code
}

此前的表单代码(会导致图表消失):

<form action="{{ route('calorietracker/weekly') }}" method="get" enctype="multipart/form-data">
   @csrf
   {{-- format of week value is "2023-W09" --}}
   <input type="week" class="week-picker" id="week_input" name="week_date" onchange="return SubmitForm(this.form);" />
</form>

路由定义:

Route::get('/calorie_tracker_weekly', [UserController::class, 'calorieTrackerWeekly'])->name('calorietracker/weekly');

问题原因

  1. 输入框未关联目标表单:当前的Week输入框没有被包裹在id="calorieBarChartWeekly"的表单中,而serialize()方法只能序列化表单内部的表单元素,因此无法获取到week_input的值。
  2. 数据序列化无效:由于没有对应的表单容器,$('#calorieBarChartWeekly').serialize()生成的参数为空,导致控制器接收不到任何数据。

解决办法

办法一:将输入框放入对应表单

修改HTML结构,把Week输入框包裹在id="calorieBarChartWeekly"的表单内:

<form id="calorieBarChartWeekly">
  <input type="week" class="week-picker" id="week_input" name="week_input" onchange="SubmitForm(event);" />
</form>

办法二:手动构造请求数据

无需依赖表单序列化,直接获取输入框的值并构造请求参数:

function SubmitForm(event) {
    event.preventDefault();
    $.ajax({
        type: 'GET',
        url: '/calorie_tracker_weekly',
        data: { week_input: $('#week_input').val() },
        success: function(data) {
            ShowChart(data);
        }
    });
}

额外注意点

确保输入框的name属性值(week_input)与控制器中$request->input('week_input')的参数名完全一致,避免因名称不匹配导致数据无法获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:05:29