【问题标题】:Collecting multiple data and send by ajax in laravel在laravel中收集多个数据并通过ajax发送
【发布时间】:2019-02-07 00:23:36
【问题描述】:

我正在使用 ajax 将我的数据发送到控制器并将其保存在数据库中,在我的代码工作之前,我需要对我的数据进行排序,当它们在排序后附加到刀片中时,它会停止工作 %50。

很高兴知道

Here is my old code and solution of sorting my data(导致 我现在遇到的这个问题)

逻辑

  1. 我选择设置
  2. 设置子元素将附加在刀片中(按自定义列排序)
  3. 我选择单个或多个选项并点击保存按钮
  4. 数据保存到数据库

更多了解

我的附加数据(基于所选集)包括两种类型的数据

  1. 我可以手动填写和保存的自定义输入(文本字段和文本区域字段)(仍然可以正常工作
  2. 从数据库返回的动态选择选项,我可以选择并保存他们的 ID(这是问题动态

代码

Script of appending data

<script defer>
$(document).ready(function() {
    $('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) {
                    $('div#dataaamsg').empty();
                    $('div#dataaamsg').append('Use <kbd>CTRL</kbd> or <kbd>SHIFT</kbd> button to select multiple options');
                    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;

                        if(value1['type'] == 'textfield'){
                            var my_row = $('<div class="row mt-20 ccin">');
                            $('div#dataaa').append(my_row);
                        }else if(value1['type'] == 'textareafield'){
                            var my_row = $('<div class="row mt-20 ccin">');
                            $('div#dataaa').append(my_row);
                        }else{
                            var my_row = $('<div class="row mt-20">');
                            $('div#dataaa').append(my_row);
                        }

                        // second data
                        $.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>';
                                });

                                if(value1['type'] == 'textfield'){
                                    var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                    my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
                                    my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                    my_row.html(my_html);
                                }else if(value1['type'] == 'textareafield'){
                                    var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                                    my_html += '<div class="col-md-6"><textarea id="longtext_dec" name="longtext_dec[]" placeholder="text area field" class="longtext_dec form-control"></textarea></div>';
                                    my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                    my_row.html(my_html);
                                }else{
                                    var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">'+value1.title+'</div>';
                                    my_html += '<div class="col-md-6"><select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">'+helpers+'</select></div>';
                                    my_html += '<div class="col-md-2"><button type="button" id="savedynspecto" class="savedynspecto btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                                    my_row.html(my_html);
                                }


                            }
                        });
                        // second data

                    });
                }
            });
        }else{
            $('div#dataaa').empty();
        }
    });
});
</script>

script of saving data (issue part)

<script defer>
  $(document).ready(function() {
   $("body").on("click", ".savedynspecto", function(e){
      var form = $(this).closest('form');
      var id = form.find('input[name="product_id"]').val();
      // e.preventDefault();
      $.ajax({
        type: "post",
        url: '{{ url('admin/spacssendto') }}',
        data: {
          '_token': $('input[name=_token]').val(),
          'product_id': id,
          'subspecifications': $(this).closest('form').find('select.subspecifications').val()
        },
        success: function (data) {
          alert('Specifications added successfully.');
          console.log($(this));
        },
        error: function (data) {
          console.log(data);
        }
      });
    });
  });
</script>

问题

  1. 当我尝试保存我的动态值时,我无法获取所选选项的 ID

    //网络参数中返回的数据 _token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu product_id 18 子规格

Ps1

我尝试将val() 更改为serialize(),我得到了

_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu
product_id 18
subspecifications subspecifications%5B%5D=20&subspecifications%5B%5D=21&subspecifications%5B%5D=23&subspecifications%5B%5D=32"

我只需要21,23,32 而不是在他们每个人之前得到subspecifications%5B%5D=

Ps2

我已尝试更改$("body").on("click", ".savedynspecto", function(e){,它不会向后端发送任何数据(网络中没有打印,甚至错误代码也没有)

有什么想法吗?

【问题讨论】:

  • 你能控制你在 $.each(data, function(key, value) { helpers += ''; });在助手中
  • 您能与我分享控制器生成的示例结果吗?
  • @ArashKhajelou 嗨,如果我使用序列化,这是我的结果array:3 [ "_token" =&gt; "Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa" "product_id" =&gt; "21" "subspecifications" =&gt; "subspecifications%5B%5D=4&amp;subspecifications%5B%5D=5&amp;subspecifications%5B%5D=22" ] 如果我使用val 这是结果array:3 [ "_token" =&gt; "Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa" "product_id" =&gt; "21" "subspecifications" =&gt; array:1 [ 0 =&gt; "3" ] ] PS:val 返回数据的方式是正确的问题是只有当我有多行时才获得第一行值总是返回第一行。

标签: javascript php jquery ajax laravel


【解决方案1】:

您好,在您的代码中更改这一行

'子规范': $(this).closest('form').find('select.subspecifications').val()

'子规范': $(this).closest('form').find('select.subspecifications option:selected').map(function(){ return this.value }).get()

应该有帮助

【讨论】:

  • 嗨,感谢您的回复。它似乎正在工作,但是使用这种方法需要一些小的改动,我不知道该怎么做。 explanation 在每个表单发送所选选项 ID 之前,当我单击保存按钮时,它只保存那些选项,这就是为什么我在刀片中为每个附加行都有保存按钮的原因,当前任何这些行上的保存按钮都将从中发送所有所选选项 ID所有行,所以我认为最好只有 1 个保存按钮 in total 而不是每行 1 个保存按钮。 Q 我怎样才能做到这一点?
  • 为了更好地理解,我制作了1ibb.co/hU1tpe2ibb.co/cpjDpe之前/之后的这些图像
  • 如果您只需要一个按钮来保存。我认为更好的方法是拆分选择并将它们发送到具有不同名称的服务器上。
  • 如何设置不同的名称?我的数据是动态的,可以是任意数量的行。
  • 能分享一下吗:1)页面的Html 2)控制器方法
【解决方案2】:

在要附加的字符串中的按钮...之后,您有{{Form::close()}}&lt;/div&gt;

我认为&lt;/div&gt; 应该在{{Form::close()}} 之前。

混乱的 HTML 结构会很快导致奇怪。
我不能 100% 确定这是问题所在……但它可以。

【讨论】:

  • 仍然发送 subspecifications empty 作为我的 issue 部分我分享了代码
  • 好吧...我的另一个想法是尝试删除name="subspecifications[]" 中的括号[],因为&lt;select multiple&gt; 的输出已经是一个数组...
  • 还是空了subspecifications
  • mmm... 在 Ajax 请求之前(您可以将其注释掉仅用于测试),试试这些 console.logs:console.log( $(this).closest('form').find('select.subspecifications').length );console.log( $(this).closest('form').find('select.subspecifications').val() )
  • 我失去了你...第一个console.log 是否返回1(所以我们确定该元素已找到)第二个是否显示具有正确值的数组?
【解决方案3】:

你有很多 selectsubspecifications 类...所以你必须遍历它们以获取它们的值。

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

      // An array to store the subspecifications values.
      var spec_array = [];

      // A loop to go through all them.
      form.find('select.subspecifications').each(function(){
        spec_array.push($(this).val());
      });

      // e.preventDefault();
      $.ajax({
        type: "post",
        url: '{{ url('admin/spacssendto') }}',
        data: {
          '_token': $('input[name=_token]').val(),
          'product_id': id,
          'subspecifications': spec_array  // The array containing each SELECT values
        },
        success: function (data) {
          alert('Specifications added successfully.');
          console.log($(this));
        },
        error: function (data) {
          console.log(data);
        }
      });
    });
  });
</script>

【讨论】:

  • 这就是我用这段代码得到的,error 500 + _token Ou5M0WwUziuG3h1WN3D0D2ND5nCtaKejZDUSEnwa product_id 21 subspecifications[] subspecifications[3][] 199 subspecifications[4][] […] 0 204 1 205
  • Error 500?我不能告诉.. 那是由于您在 Ajax 调用的资源上拥有的代码。也就是说,肯定,另一个问题。现在你已经发送了一些关于每个 SELECT 的数据,这很好......这就是你的问题的主题。
  • 无论如何,谢谢,我看看其他人是否有其他解决方案:/对此感到困惑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 2017-02-23
  • 2021-02-24
  • 2014-04-06
  • 1970-01-01
  • 2013-07-04
相关资源
最近更新 更多