【问题标题】:Foreach Condition with Ajax form submit button带有 Ajax 表单提交按钮的 Foreach 条件
【发布时间】:2021-10-18 23:46:44
【问题描述】:

我试图为表单的每个条件做,但由于某种原因,它正在使用 ajax 提交所有 foreach 数据。

@foreach($response['Types'] as type)
  <div class="option option-two">
    <div class="upper">
        <p style="font-size: 2em;font-weight: bold">${{ number_format($type['price']['subTotal'],2)}}</p>
        <p style="font-weight: bold">Per Day Parking</p>
    </div>
    <div class="form">
        <form name="{{$type['id']}}"  method="post" class="reds">
            @CSRF
            {{--<input type=hidden name=LotId value="{{ json_encode($response, true) }}">--}}
            <input type=hidden name=subtotal value="{{ number_format($type['price']['subTotal'],2) }}">
            <input type=hidden name=fees value="{{ number_format($type['price']['taxesAndFeesAmount'],2) }}">
            <input type=hidden name=total value="{{ number_format($type['price']['total'],2) }}">

            <button id="chkbtn" style="box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2), 0 2px 10px 0 rgba(0, 0, 0, 0.1);">Add to Cart</button>
        </form>
        <script>
            $(function () {

                $("form[name='{{$type['id']}}']").submit(function(e){

                    e.preventDefault();

                    $.ajax({
                        type: 'post',
                        url: '/options1',
                        data: $('form').serialize(),
                        success: function (result) {
                            $("#iDiv").html(result);
                        }
                    });

                });


            });
        </script>
@endforeach

由于某种原因,响应是

_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 23.90
fees: 4.99
total: 28.89
_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 23.90
fees: 4.99
total: 28.89
_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 27.90
fees: 4.99
total: 32.89

我只想向购物车发送一个选项数据。但是,它将所有 foreach 数据添加到购物车

请帮忙,谢谢

【问题讨论】:

  • @foreach($response['Types'] as type) 中的type 不应该是$type吗?

标签: javascript php jquery laravel


【解决方案1】:
data: $('form').serialize()

这将序列化加载在网页上的所有表单。相反,您应该只序列化提交的表单,就像您对提交事件处理程序所做的那样。

data: $("form[name='{{$type['id']}}']").serialize()

或简写

data: $(this).serialize()

将仅序列化特定表单而不是所有表单。

【讨论】:

  • 鉴于它在表单的 submit 处理程序中,您也可以只使用$(this).serialize()
  • 同意,也可以。
猜你喜欢
  • 2014-11-25
  • 1970-01-01
  • 2014-12-11
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 2015-05-25
  • 1970-01-01
相关资源
最近更新 更多