【问题标题】:How to save array from XMLHTTPREQUEST API POST to Laravel Controller如何将数组从 XMLHTTPREQUEST API POST 保存到 Laravel 控制器
【发布时间】:2020-10-19 10:29:22
【问题描述】:

我想将我的数组保存在从 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;

}

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

【问题讨论】:

  • 请告诉我们您收到的错误。
  • 您只是缺少添加:$country->save(),它会起作用
  • 我没有收到任何错误,我只是无法将数组保存到数据库:D

标签: javascript php laravel api xmlhttprequest


【解决方案1】:

来自文档: “您也可以使用create() 方法将新模型保存在一行中。”

您使用create() 方法有点错误,因为:“一旦我们使属性可以批量分配,我们就可以使用 create 方法在数据库中插入一条新记录。”

所以要么使用 $country->save(); 方法而不是代码中的 return $country 国家模式如:

class Country extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['country_code', 'country_name'];
}

然后在你的 Controller 中你可以使用:

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() 方法返回保存的模型实例:

文档链接: https://laravel.com/docs/7.x/eloquent#mass-assignment

现在,再看看你的代码,你绝对不可能没有错误(在你的浏览器控制台中),因为我没有看到任何 CSRF 令牌 随您的请求一起发送,XMLHttpRequest.send() 方法不会像您尝试的那样将您的数据传递给您的 Laravel 控制器,因为数据必须采用特定格式。

所以请确保您拥有 CSRF 令牌。最简单的方法是将其包含在您的 html head 中,例如:

<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
</head>

那么 token 也必须包含在 Javascript 脚本中。您将在下面的脚本中找到它。

并且由于您要发送的数据看起来像一个关联的数据数组,因此它应该包含在 FormData 对象中(作为send() 方法的适当格式)并且这样您不会遇到数据格式和在控制器中获取数据的问题。所以它会按原样工作。您的脚本应如下所示:

<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>

我希望您可以通过上述改进使其正常工作。如果您的路由和 URL 都正常,它一定可以工作。

【讨论】:

  • 感谢您的回答???? ????
【解决方案2】:

这样试试

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

【讨论】:

  • 感谢您的回答,但它对我不起作用??,您有其他方法吗?
猜你喜欢
  • 2019-09-23
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多