繁体   English   中英

如何在Laravel中使用Ajax将数据数组发送到控制器

[英]How to send array of data to controller with ajax in laravel

我想一次将数据数组发送到后端,但是我不能。

问题

1.这是我目前发送的

array:5 [
  "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj"
  "product_id" => "21"
  "specification_id" => "6"
  "text_dec" => "1"
  "longtext_dec" => null
]

应该是这样的:

Array [
  0 = [
    data
  ]
  1 = [
    data
  ]
  2 = [
    data
  ]
]
  1. 我总是获得与specification_id相同的ID ,而刀片中的每一行都有不同的ID

appending script

<script defer>
    $(document).ready(function() {
//select the category
        $('select[name="selectset"]').on('change', function() {
            var id = $(this).val();
            if(id) {
                $.ajax({
                    url: '{{ url('admin/selectset') }}/'+encodeURI(id),
                    type: "GET",
                    dataType: "json",
                    success:function(result) {
//sort the results
                        result.sort(function(a,b) {
                            return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);
                        });


                        $.each(result, function(key1, value1) {

                            var vvvid = value1.id;

//textfield and textareafield are part of my issue (appended rows)
                            if(value1['type'] == 'textfield'){
                                var my_row = $('<div class="row mt-20 ccin">');
                                $('div#dataaa').append(my_row);
                            }else{
                                var my_row = $('<div class="row mt-20 ccin">');
                                $('div#dataaa').append(my_row);
                            }

                            // second data (get values)
                            $.ajax({
                                url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
                                type: "GET",
                                dataType: "json",
                                success:function(data) {
                                    // Check result isnt empty
                                    var helpers = '';
                                    $.each(data, function(key, value) {
                                        helpers += '<option value="'+value.id+'">'+value.title+'</option>';
                                    });


//this is the part of my issue
                                    if(value1['type'] == 'textfield'){
                                        var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                        my_html += '<div class="col-md-6"><input id="text_decc" name="text_decc" placeholder="text field" class="text_decc form-control"></div>';
                                        my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                        my_row.html(my_html);
                                    }else{ //second part of my issue
                                        var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                        my_html += '<div class="col-md-6"><textarea id="longtext_decc" name="longtext_decc" placeholder="text area field" class="longtext_decc form-control"></textarea></div>';
                                        my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                        my_row.html(my_html);
                                    }


                                }
                            });
                            // second data

                        });
                    }
                });
            }
        });
    });
</script>

上面代码的结果如下:

一

saving script 应修复的部分

<script>
$(document).ready(function() {
  $("body").on("click", ".custmodalsaveee", function(e){
        var id = $('input[name="product_id"]').val();

        $.ajax({
          type: "post",
          url: "{{ url('admin/addnewcustomsubspecifications') }}",
          data: {
            '_token': $('input[name=_token]').val(),
            'product_id': id,
            'specification_id': $('.specification_idd').val(),
            'text_dec': $('.text_decc').val(),
            'longtext_dec': $('.longtext_decc').val(),
          },
          success: function (data) {
            alert('Specification added successfully in your product!');
          },
          error: function (data) {
            console.log('Error!', data);
          }
        });
  });
  });
</script>

controller

public function addnewcustomsubspecifications(Request $reqss){
        dd($reqss->all());

    //   $this->validate($reqss, array(
    //     'product_id' => 'required',
    //     'specification_id' => 'required',
    //     'text_dec' => 'nullable',
    //     'longtext_dec' => 'nullable',
    //   ));


    //   $add = CustomProductSpecification::create([
    //       'product_id' => $reqss->product_id,
    //       'specification_id' => $reqss->specification_id,
    //       'text_dec' => $reqss->text_dec,
    //       'longtext_dec' => $reqss->longtext_dec,
    //   ]);
    //   $parent = Specification::where('id', '=', $reqss->specification_id)->first();
    //   return response()->json(array('data'=>$add,'parent'=>$parent));
}

任何想法?

更新

HTML输出

二

UPDATE2

因此,根据我使用.map()建议,这是我的代码和结果

script

$(document).ready(function() {
  $("body").on("click", ".custmodalsaveee", function(e){
        var id = $('input[name="product_id"]').val();

        var specification_idd = $( ".ccin" ).map(function() {
            return $( this ).find('.specification_idd').val();
            return $( this ).find('.text_decc').val();
            return $( this ).find('.longtext_decc').val();
        }).get();
        var text_decc = $( ".ccin" ).map(function() {
            return $( this ).find('.text_decc').val();
        }).get();
        var longtext_decc = $( ".ccin" ).map(function() {
            return $( this ).find('.longtext_decc').val();
        }).get();
  console.log(specification_idd);
  console.log(text_decc);
  console.log(longtext_decc);

        $.ajax({
//rest of it as it was...

和控制台结果

三

  1. 如何获得相关结果? specification_idtext fields为1个数组
  2. 我如何避免空值? 如果text_declongtext_dec是空的每个specification_id不需要是发送 example规范40不具有任何值longtext_dectext_dec不需要被发送

罗伯特,您应该在laravel方法中直接从Ajax调用返回视图,并将视图的html响应与新数据绑定在一起。

那是很简单的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM