Laravel中Ajax请求无法向控制器方法传递数据的问题
解决Laravel Ajax请求无法传递参数到控制器的问题
问题根源
你当前的Ajax请求存在参数格式与请求头不匹配的问题:
- 你将数据用
JSON.stringify()转成了JSON字符串,但设置的contentType是application/x-www-form-urlencoded(表单编码格式) - 同时开启了
processData: false,阻止jQuery自动处理数据格式,导致Laravel无法正确解析请求体中的数据,因此所有获取参数的方式都返回null
解决方案一:使用表单编码格式传递数据(推荐,适合简单参数)
修改你的Ajax代码,直接传递原始对象,不需要转成JSON字符串:
var token = $('meta[name="csrf-token"]').attr('content'); var inputValue = "Testing"; var anotherInput = "Testing2"; var data = { anotherInput: anotherInput, inputValue: inputValue, _token: token // 这里带_token即可,不需要重复在headers里设置 }; $.ajax({ url: postUrl, type: 'POST', data: data, // 直接传递对象,jQuery会自动转成表单格式 dataType: 'json', // contentType可以省略,默认就是application/x-www-form-urlencoded success:function(response) { console.log(response); }, error: function(response) { console.log(response); } });
控制器代码无需修改,之前的$request->input('anotherInput')、$request->anotherInput等方式都能正常获取参数。
解决方案二:使用JSON格式传递数据(适合复杂结构参数)
如果需要传递JSON格式的数据,需要调整请求头并修改控制器的参数获取方式:
- 修改Ajax代码的
contentType为application/json:
var token = $('meta[name="csrf-token"]').attr('content'); var inputValue = "Testing"; var anotherInput = "Testing2"; var data = { anotherInput: anotherInput, inputValue: inputValue }; $.ajax({ url: postUrl, type: 'POST', headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json' // 明确设置JSON格式请求头 }, data: JSON.stringify(data), dataType: 'json', processData: false, success:function(response) { console.log(response); }, error: function(response) { console.log(response); } });
- 在控制器中通过
$request->json()方法获取JSON参数:
public function filePathTest(Request $request) { // 获取所有JSON参数 $data = $request->json()->all(); // 获取单个参数 $anotherInput = $request->json('anotherInput'); $response = [ 'msg' => $data, 'anotherInput' => $anotherInput ]; return response()->json($response); }
额外注意事项
- CSRF Token:Laravel中只需在请求中携带一次即可,要么在
data里带_token,要么在headers里带X-CSRF-TOKEN,无需重复设置 - 路由配置:你的
Route::match同时支持GET和POST,测试时注意不要用GET请求(GET请求无法携带请求体参数)
内容的提问来源于stack exchange,提问作者John T
相关产品推荐
相关产品推荐

