javascript - 如何将数组从 XMLHTTPREQUEST API POST 保存到 Laravel 控制器
问题描述
我想将我的数组保存在从 Javascript XMLHTTP 请求发送的数据库中。
Javascript
function 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);
var singlevar = {"country_name":"Indonesia","country_code":"ID"}
xhttp.send(singlevar);
}
laravel 中的控制器
public function postdata(Request $request)
{
$country = Country::create([
'country_code' => $request->get('country_code'),
'country_name' => $request->get('country_name'),
]);
return $country;
}
使用此代码,我无法保存到数据库。
解决方案
像这样试试
try{
$country = new Country();
$country->country_code = $request->get('country_code');
$country->country_name = $request->get('country_name');
$country->save();
}
catch(\Exception $e){
dd($e->getMessage());
}
推荐阅读
- python - Python - 连接特定目录中的 CSV 文件
- apache-spark - Apache Spark 2.1 中缺少 LinearSVC?Spark 2.2 中的非线性内核?
- java - 使用 Java Stream API 对 BigDecimal 进行分组和累加
- c++ - Boost Beast编译错误
- php - 如何在 PHP 的 SOAP API 中调用和设置标头和函数中的参数?
- regex - 如何从 html 文件中提取 URL 路径?(在 bash 中)
- java - anagramManager程序不同区域的空指针异常错误
- html - 响应性不适用于忘记密码链接
- angular - @NgModule 的意外令牌
- linux - Expo reload 在 Linux 上不起作用(使用 Android 设备)