首页 > 解决方案 > 如何将数组从 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;

}

使用此代码,我无法保存到数据库。

标签: javascriptphplaravelapixmlhttprequest

解决方案


像这样试试

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());
}

推荐阅读