XMLHTTPREQUEST POST数组至Laravel控制器存库失败,求解决方法
问题分析与解决方案
你的代码无法将数据保存到数据库,核心问题在于XMLHttpRequest发送数据的格式不正确,同时没有设置对应的请求头,导致Laravel控制器无法正确解析你传递的参数。下面分两种常用的修复方案来解决这个问题:
方案1:使用表单编码格式发送数据(传统键值对场景)
这种方式和HTML表单提交的格式一致,适合简单的键值对数据:
修改JavaScript代码
需要把JS对象转为URL编码的字符串,并设置正确的请求头:
xml2() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(JSON.parse(this.responseText)); } }; xhttp.open("POST", "http://localhost/sekai_adminlte3_rnd/api/rnd/postdata", true); // 告诉服务器我们发送的是表单编码格式的数据 xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var singlevar = {"country_name":"Indonesia","country_code":"ID"}; // 将对象转换为URL编码的键值对字符串 var formData = Object.keys(singlevar).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(singlevar[key])}` ).join('&'); xhttp.send(formData); }
Laravel控制器代码(无需修改)
你的原控制器代码可以直接使用,$request->get()能正确解析表单编码的参数:
public function postdata(Request $request) { $country = Country::create([ 'country_code' => $request->get('country_code'), 'country_name' => $request->get('country_name'), ]); return response()->json($country); // 建议明确返回JSON格式响应 }
方案2:使用JSON格式发送数据(推荐,适配复杂数据结构)
如果之后需要发送数组或嵌套结构的数据,JSON格式会更灵活易用:
修改JavaScript代码
把对象转为JSON字符串,设置请求头为application/json:
xml2() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(JSON.parse(this.responseText)); } }; xhttp.open("POST", "http://localhost/sekai_adminlte3_rnd/api/rnd/postdata", true); // 告诉服务器我们发送的是JSON格式数据 xhttp.setRequestHeader("Content-Type", "application/json"); var singlevar = {"country_name":"Indonesia","country_code":"ID"}; // 将对象转为JSON字符串发送 xhttp.send(JSON.stringify(singlevar)); }
修改Laravel控制器代码
需要从JSON请求体中获取数据(Laravel 5.5+会自动解析JSON到请求对象,但显式处理更稳妥):
public function postdata(Request $request) { // 从JSON请求体中提取所有数据 $data = $request->json()->all(); $country = Country::create([ 'country_code' => $data['country_code'], 'country_name' => $data['country_name'], ]); return response()->json($country); // 明确返回JSON响应 }
额外必查事项
- 模型批量赋值权限:确保你的
Country模型设置了$fillable属性,否则Laravel的批量赋值保护会阻止数据写入:
class Country extends Model { protected $fillable = ['country_code', 'country_name']; }
- 路由配置:确认你的
api.php中正确配置了POST路由:
Route::post('/rnd/postdata', [YourController::class, 'postdata']);
- 跨域问题:如果前端页面和后端API不在同一端口/域名,需要处理CORS问题(可以使用
barryvdh/laravel-cors包快速配置)。
内容的提问来源于stack exchange,提问作者Zenryo Naufal
相关产品推荐
相关产品推荐

