douhuan6065
2018-06-02 19:13
浏览 55
已采纳

如何使用ajax和laravel 5.6保存多个输入和文件

I have about twenty text-box, checkbox and select as well as four file type inputs. I would like to save the input to a database using Laravel and AJAX.

Actually, I can save all inputs except file type (images).

Table: META | VALUE

My route: $this::resource('/settings','SettingController')->only(['index', 'store']);

Controller:

$setting = $request->all();
foreach ($setting as $meta => $value) {
    $SF = new Setting();
    $SF->meta = $meta;
    $SF->value = $value;
    echo  $SF->save();
}

HTML:

<form>
 <input type="text" name="site_title"  id="site-title">
 <input type="checkbox" name="register"  id="register">
  ....
 <input type="file" name="logo"  id="logo">
 <input type="file" name="favicon"  id="favicon">
 <input type="file" name="user_profile"  id="user_profile">
 <input type="file" name="Personal"  id="Personal">

AJAX code:

 $('#setting-forms').on('submit', function () {
    event.preventDefault();
    let _token =  $('input[name=_token]').val();  //Get Token
    let FormInputs = $("#setting-forms").serialize(); 

    $.ajax({
        method: 'POST',
        url: '/settings',
        data: FormInputs ,

        success: function (data) {
          //Some Success MSG

        },
        error: function () {
             //Some Error MSG
        },
    });

Now, this code saves all inputs except file types and my result is something like this :

     META     |     VALUE
--------------+--------------
   site_title |   Laravel
    register  |     On
      ....    |     ...

But I want save all image files too, so I changed my AJAX code to the following:

 let formData = new FormData();
 let logo = $("#logo")[0].files[0];
 formData.append('logo', logo);
 formData.append('FormInputs', FormInputs);
 $.ajax({
        method: 'POST',
        url: '/settings',
        data: formData,
        contentType: false,
        processData: false,
        headers: {
            'X-CSRF-TOKEN': _token
        },

Now I can save logos but my text is all saved on a single row. I get this:

     META     |                Value
--------------+-----------------------------------
     Logo     |               MyLOGO
   FormInputs |  site_title=titlea&register=on&...

While I would like something like that:

     META     |     VALUE
--------------+--------------
    Logo      |    MyLOGO
  site_title  |    title
   register   |     On

How can I fix this?

1条回答 默认 最新

相关推荐 更多相似问题