首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何防止ajax post请求提交两次?

如何防止ajax post请求提交两次?
EN

Stack Overflow用户
提问于 2021-03-02 13:56:31
回答 3查看 152关注 0票数 2

我有一个按钮subscribe,它应该通过ajax向我的控制器提交一个post请求,以便插入到我的表中。

我的视图是这样的:

代码语言:javascript
运行
复制
@extends('layouts.app')

@section('content')

    
        
            
            
                
                    
                        {{$thread->creator->name}} posted:
                            {{$thread->title}}
                        
                        @if(auth()->check())
                        @if($subscription)
                        Unsubscribe
                        @else
                        Subscribe
                        @endif
                        @endif
                        @can('update',$thread)
                        Edit Thread
                        
                            @csrf
                            @method('delete')
                            Delete Thread
                        
                        @endcan
                    
                
                
                {{$thread->body}}
                
            

..............

My app.blade:



    
    

    
    

    {{ config('app.name', 'Laravel') }}

    
    

    
    
    

    
    
    

    
    
    
        body{
            padding-bottom:100px;
        }
        .level{
            display: flex;
            align-items: center;
        }
        .flex{
            flex: 1;
        }
    


      
        @include('layouts.nav')
        
            @yield('content')
        
    
    



    .btn-width{
        min-width: 70px;
      }






The code calling the button:


    $(document).ready(function(){
        $('#subscribe').click(function(e){
            e.preventDefault();
            $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                  }
              });
              
            $.ajax({
                url: "{{route('subscription.store')}}",
                method:'POST',
                data: {
                    thread_id: "{{$thread->id}}",
                },
                success:function(response){
                    $('div.flash-message').html(response);
                   
                },
                error:function(error){
                    console.log(error);
                }
            });
        });
    });

From what I could tell, there is no other element that shares the same id as my button. And, my button is not in a form submit so it should not be called twice. Inspecting dev tools shows no error and in the network tab, two requests are called identically with the same initiator.

So, I am kinda wondering why would this happen. Shouldn't an ajax post request submit the request once only?

I would really like to get to the bottom of this as most of the other similar issues have calling the submit twice while my code is only supposed to call it once. Instead, it makes two insertion to my db.

What else can I do to figure out the root cause of the issue?

EN

回答 3

Stack Overflow用户

发布于 2021-03-02 14:19:59

有没有可能你的javascript以某种方式被加载了两次?这将附加两个相同的侦听器,并在一次单击中发送两次请求。如果将console.log放在事件处理程序中,是否也会看到两倍的效果?

另外,很明显,

为与传递给jQuery对象的选择器匹配的每个元素添加单独的事件侦听器,而

仅添加一个。

..。如果你这样做会发生什么呢?

代码语言:javascript
运行
复制
$(document).ready(function () {
  $("#subscribe").on("click", function(e) {
    e.preventDefault();
    $.ajaxSetup({
      headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
      },
    });

    $.ajax({
      url: "{{route('subscription.store')}}",
      method: "POST",
      data: {
        thread_id: "{{$thread->id}}",
      },
      success: function (response) {
        $("div.flash-message").html(response);
      },
      error: function (error) {
        console.log(error);
      },
    });
  });
});
票数 1
EN

Stack Overflow用户

发布于 2021-03-02 14:15:32

您正在调用您的函数两次,第一次是在文档就绪中,第二次是在按钮单击删除程序文档中

票数 0
EN

Stack Overflow用户

发布于 2021-03-02 14:19:37

你有没有试过返回false?如下所示:

代码语言:javascript
运行
复制
$(document).ready(function(){
    let subscribeClick = function() {
     $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          
        $.ajax({
            url: "{{route('subscription.store')}}",
            method:'POST',
            data: {
                thread_id: "{{$thread->id}}",
            },
            success:function(response){
                $('div.flash-message').html(response);
               
            },
            error:function(error){
                console.log(error);
            }
        });
        return false;
    }
    $('#subscribe').click(function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        subscribeClick(); 
    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66434045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档