Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

javascript - 如何处理接收到的数据以将其保存在数据库Laravel和Ajax中?(How to handle the data received to save it in the database Laravel and Ajax?)

I'm trying to add the product with multiple images to the database without refreshing the page, I don't get any errors on console but I see the long text which starting like this

(我正在尝试将具有多个图像的产品添加到数据库而不刷新页面,控制台上没有出现任何错误,但是我看到的长文本是这样的)

<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|[]/\])/g, idRx = /sf-dump-d+-ref[012]w+/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = ....

and the error comes from this line console.log(data);

(并且错误来自此行console.log(data);)

.

(。)

The product has a relationship with ProductsPhoto,how can I make it add the product to the database?

(该产品与ProductsPhoto有关系,如何使该产品添加到数据库中?)

Controller

(控制者)

 public function store(Request $request)
 {
    $formInput=$request->except('filename');

    $product = product::create(array_merge($formInput, [
        'seller_id'=> Auth::user()->id,
        'user_id' => Auth::user()->id
    ]));
    foreach ($request->photos as $photo) {
       $filename = $photo->store('public/photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
    }
}

Blade

(刀)

  <div class="panel-body">

   <input type="hidden" value="{{csrf_token()}}" id="token"/>

     <label for="pro_name">Name</label>
      <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

        <label for="pro_price">Price</label>
           <input type="text" class="form-control" name="pro_price" id="pro_price" placeholder="Enter price">

        <label for="pro_info">Description</label>
         <input type="text" class="form-control" name="pro_info" id="pro_info" placeholder="Enter product description">

           <label for="stock">Stock</label>
            <input type="text" class="form-control" name="stock" id="stock" placeholder="Enter stock">

        <label  for="category_id">Choose Category</label>
           <select name="category_name" id="category_name">
             <option value=""> --Select Category -- </option>
               @foreach ($categoryname_array as $data)
                <option value="{{ $data->name }}"  >{{$data->name}}</option>
                 @endforeach
               </select>

 <label for="photos">Choose 5 Images</label>
  <input  "multiple="multiple" id="photos" name="photos[]" type="file">

  <input type="submit" class="btn btn-primary" value="Submit" id="btn"/>

</div>

Ajax

(阿贾克斯)

   $(document).ready(function(){
   $("#btn").click(function(){
    var category_name = $("#category_name").val()
    var pro_name = $("#pro_name").val();
    var pro_price = $("#pro_price").val();
    var stock = $("#stock").val();
    var pro_info = $("#pro_info").val();
    var photos = $("#photos").val();
    var token = $("#token").val();

    $.ajax({

        type: "post",
        data: "pro_name=" + pro_name + "&pro_price=" + pro_price + "&stock=" + stock + "&_token=" + token + "&category_name=" + category_name + "&pro_info=" + pro_info + "&photos=" + photos,
        url: "<?php echo url('seller/product') ?>",
        success:function(data){
        console.log(data);
        }

    });
  });
});

Route

(路线)

 Route::post('seller/product', 'ProductController@store')->name('product.store');
  ask by joh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the error you added in the comments, the value inside $request->photos is not iteratable, which make sense because you do not use Form Data to handle upload.

(根据您在注释中添加的错误, $request->photos值不可迭代,这是有道理的,因为您没有使用表单数据来处理上传。)

Normal ajax does not handle file upload so you have to use formData :

(普通的ajax无法处理文件上传,因此您必须使用formData :)

var token = $("#token").val();
$(document).ready(function(){
    $("#btn").click(function(){
        var form = $('form')[0]; // You need to use standard javascript object here
        var formData = new FormData(form);
        formData.append('_token', token); // adding token
        $.ajax({
            url: "<?php echo url('seller/product') ?>",
            data: formData, //just that without variables
            type: 'POST',
            contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
            processData: false, // NEEDED, DON'T OMIT THIS
            success:function(data){
                console.log(data);
            }
        });
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...