首页 文章

提交按钮在ajax函数[暂停]之前触发get submit

提问于
浏览
1

我是Ajax的新手,所以这是我第一次尝试将laravel和Ajax绑定在一起 . 无论如何,我已经理解了它的全部内容和所有内容,但是当我尝试使用提交按钮发布数据时,数据作为get方法传递,就好像代码永远不会到达ajax函数 .

这是我的形式:

<form id="addtocart">
                <button class="btn btn-outline-primary btn-lg" type="submit">add to cart</button>
            <input id="name" type="hidden" value="{{$one->name}}" name="data">
            <input id="price" type="hidden" value="{{$one->price}}" name="price">
            <input id="image" type="hidden" value="{{$one->image_path}}" name="image">
</form>

我的Ajax功能:

jQuery(document).ready(function(){
  jQuery('#addtocart').submit(function(e){
     e.preventDefault();
     $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
     jQuery.ajax({
        url: "{{ url('/addtocart') }}",
        method: 'post',
        data: {
           name: jQuery('#name').val(),
           image: jQuery('#image').val(),
           price: jQuery('#price').val()
        },
        success: function(result){
           jQuery('.alert').show();
           jQuery('.alert').html(result.success);
        }});
     });
  });

谢谢你的帮助 !!! (我认为脚本最初没有运行,因为我在ajax函数之后包含了jquery库..但事实并非如此)

3 回答

  • 0

    form 标记内插入 method="post"

    <form id="addtocart" method="post">
                    <button class="btn btn-outline-primary btn-lg" type="submit">add to cart</button>
                <input id="name" type="hidden" value="{{$one->name}}" name="data">
                <input id="price" type="hidden" value="{{$one->price}}" name="price">
                <input id="image" type="hidden" value="{{$one->image_path}}" name="image">
    </form>
    

    希望它会起作用

  • 1

    为什么不在按钮中添加id

    <button id="addtocart" class="btn btn-outline-primary btn-lg" type="submit">add to cart</button>
    

    然后将事件侦听器分配给按钮单击:

    jQuery('#addtocart').on('click', function(e){}); // the closure body should be the same.
    
  • 0

    在表单标记中,将action属性分配给hashtag值 .

    <form id="addtocart" action="#">
                    <button class="btn btn-outline-primary btn-lg" type="submit">add to cart</button>
                <input id="name" type="hidden" value="{{$one->name}}" name="data">
                <input id="price" type="hidden" value="{{$one->price}}" name="price">
                <input id="image" type="hidden" value="{{$one->image_path}}" name="image">
    </form>
    

    没有它,表单将首先执行,这就是为什么ajax脚本没有捕获提交函数 .

相关问题