Javascript 如何将XMLHttpRequestAPI POST中的数组保存到Laravel控制器
我想将数组保存在数据库中,从Javascript XMLHTTP请求发送 JavascriptJavascript 如何将XMLHttpRequestAPI POST中的数组保存到Laravel控制器,javascript,php,laravel,api,xmlhttprequest,Javascript,Php,Laravel,Api,Xmlhttprequest,我想将数组保存在数据库中,从Javascript XMLHTTP请求发送 Javascript function xml2() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(JSON.parse(this.re
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());
}
来自文档:“您还可以使用
create()
方法在单行中保存新模型。”
您使用的create()
方法有点错误,因为:“一旦我们使属性可分配,我们就可以使用create方法在数据库中插入新记录。”
因此,要么使用$country->save()
方法而不是返回代码中的$country
,或更好,使国家/地区模型中的字段可填充(质量可分配),如下所示:
class Country extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['country_code', 'country_name'];
}
然后在控制器中可以使用:
public function postdata(Request $request)
{
$country = Country::create([
'country_code' => $request->get('country_code'),
'country_name' => $request->get('country_name'),
]);
// return $country; // this one is not needed at all
}
create()
方法返回保存的模型实例:
链接到文档:
现在,再看一下您的代码,您绝对不可能没有错误(在浏览器控制台中),因为我没有看到随您的请求一起发送的CSRF令牌以及XMLHttpRequest.send()
方法不会在您尝试时将数据传递给Laravel控制器,因为数据必须采用特定格式
因此,请确保您拥有CSRF令牌。最简单的方法是将其包含在html头中,如:
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
我希望您能通过上述改进使其正常工作。如果你的路由和URL正常,它必须工作。请告诉我们你收到的错误。你只是缺少添加:$country->save()
,它会工作的。我没有收到任何错误,我只是无法将数组保存到数据库:谢谢你的回答,但这不是我的工作。谢谢你的回答
<script>
function xml2() {
var xhttp = new XMLHttpRequest();
let token = document.querySelector('meta[name="csrf-token"]').content;
xhttp.open("POST", "/sekai_adminlte3_rnd/api/rnd/postdata", true);
xhttp.setRequestHeader('X-CSRF-TOKEN', token);
var singlevar = new FormData;
singlevar.append('country_name', 'Indonesia');
singlevar.append('country_code', 'ID');
xhttp.send(singlevar);
}
</script>