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

Laravel项目中如何用Axios获取表单值并传递至控制器?

当然可行!你的思路完全没问题,只是FormData的使用方式有个小疏漏,我来帮你修正并说明细节:

问题根源

你当前创建的FormData实例是空的,没有把表单里的输入值添加进去,所以后端控制器自然拿不到firstname和lastname的数据。

解决方案1:自动收集整个表单数据(推荐)

直接把表单DOM元素传给FormData的构造函数,它会自动收集所有带name属性的输入字段值,代码修改如下:

$('#getdata').on('click', function(e) {
    // 阻止按钮的默认提交行为,避免页面刷新打断Axios请求
    e.preventDefault();
    
    // 获取表单DOM元素
    const formElement = document.getElementById('reportData');
    // 传入表单元素,自动收集所有字段
    const formreport = new FormData(formElement);

    axios.post('/report/draft', formreport)
        .then(function (response) {
            console.log('响应数据:', response);
        })
        .catch(function (error) {
            // 增加错误捕获,方便调试
            console.error('请求出错:', error);
        });
});

解决方案2:手动添加指定字段

如果只需要收集部分字段,或者要额外添加其他数据,可以用FormData.append()方法手动添加:

$('#getdata').on('click', function(e) {
    e.preventDefault();
    
    const formreport = new FormData();
    // 根据name属性获取输入值并添加到FormData
    formreport.append('firstname', $('input[name="firstname"]').val());
    formreport.append('lastname', $('input[name="lastname"]').val());
    // 还可以添加其他自定义字段,比如:formreport.append('draft_status', 'pending');

    axios.post('/report/draft', formreport)
        .then(function (response) {
            console.log('响应数据:', response);
        })
        .catch(function (error) {
            console.error('请求出错:', error);
        });
});

后端控制器验证

确保你的路由和控制器代码正确,比如:

  1. 在routes/web.php中定义路由:
use App\Http\Controllers\ReportController;

Route::post('/report/draft', [ReportController::class, 'storeDraft']);
  1. 在ReportController中编写处理方法:
use Illuminate\Http\Request;

public function storeDraft(Request $request)
{
    // 直接通过$request->name获取对应字段值
    $firstname = $request->firstname;
    $lastname = $request->lastname;

    // 这里可以添加数据验证、存储逻辑等
    // 示例:返回JSON响应
    return response()->json([
        'success' => true,
        'data' => [
            'firstname' => $firstname,
            'lastname' => $lastname
        ]
    ]);
}

注意事项

  • 表单输入元素必须要有name属性(你的代码里已经满足,这点很好),FormData是根据name来识别字段的。
  • 发送FormData时,不需要手动设置Content-Type,Axios会自动设置为multipart/form-data并带上正确的边界标识。
  • 记得添加错误捕获逻辑,方便排查请求失败的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:52:39