【问题标题】:How to insert inputs to database in Laravel using ajax with jquery.serializeJSON package?如何使用带有 jquery.serializeJSON 包的 ajax 将输入插入 Laravel 中的数据库?
【发布时间】:2021-01-01 17:08:36
【问题描述】:

我需要您的帮助,如何使用 ajax 插入输入数据?旁注我正在使用 jquery.serializeJSON 包从用户那里获取 json 对象输入。提交时会显示错误 419。下面是我的html代码

<form  id="myform">
    @csrf
<input type="text" name="name" value="Jake Zyrus">
  <input type="text" name="description[name]" value="John Smith"/>
  <input type="text" name="description[job]"  value="Legendary Pirate"/>
  <input type="text" name="description[car]"  value="Delorean"/>
  <button type="submit" >Add</button>
</form>

<script type="text/javascript">
    $(document).ready(function(){

       var employee = $('#myform').serializeJSON();
       var employees = JSON.stringify(employee);
       
      
      $('#myform').submit(function(){

        $.ajax({

            type: "POST",
            url: "/insert",
            data: employees,
            success: function(response){
                alert("Data Save");
            },
            error: function(error){
                alert("Didnt Save");

            }

        });

      });

     
    });

   
</script>

虽然这是我的控制器文件

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\job;
class JobController extends Controller
{
        public function create(Request $request){
            $jobs = new job;
            $jobs->name = $request->input('name');
            $jobs->description[] = $request->input('description');
            $jobs->save();
            return redirect('home');
        }
}

最后这是模型应用文件

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
class job extends Model
{
    //

    protected $table = 'jobs';
    protected $casts = [
        'description' => 'array'
    ];

   

}

提前感谢您的回复。将不胜感激。

【问题讨论】:

    标签: jquery json ajax laravel


    【解决方案1】:

    由于您使用ajax请求保存数据,您可以直接使用$request-&gt;name访问序列化的表单数据。

    【讨论】:

    • 你的意思是$jobs->name = $request->name;?还是一样,它显示了一些错误
    猜你喜欢
    • 2020-02-10
    • 2021-05-10
    • 1970-01-01
    • 2020-11-13
    • 2021-05-11
    • 2018-08-06
    • 1970-01-01
    • 2015-05-01
    • 2023-03-03
    相关资源
    最近更新 更多