Prevent ajax call from firing twice

后端 未结 5 915
遥遥无期
遥遥无期 2020-12-05 20:20

I have an ajax call

$(\'#button1\').on(\'click\', function(e){
    $.ajax({
      url:  url,
      type: \'POST\',
      async: true,
      dataType: \'json\         


        
相关标签:
5条回答
  • 2020-12-05 20:33

    Simply call .off() right before you call .on().

    This will remove all event handlers:

    $(element).off().on('click', function() {
        // function body
    });
    

    To only remove registered 'click' event handlers:

    $(element).off('click').on('click', function() {
        // function body
    });
    
    0 讨论(0)
  • 2020-12-05 20:33

    As per the answer by Brennan,

    $('#button1').on('click', function(e){
        $('#button1').attr('disabled', 'disabled');
        $.ajax({
          url:  url,
          type: 'POST',
          async: true,
          dataType: 'json',
          enctype: 'multipart/form-data',
          cache: false,
          success: function(data){
             $('#button1').removeAttr('disabled');
          },
          error: function(){}
        });
        e.stopImmediatePropagation();
        return false;
    });
    

    Here the button will be disabled and will be enabled on success

    0 讨论(0)
  • 2020-12-05 20:35

    I was facing the same issue and it works when I set async: false. Sample code will be like this

    $('#button1').on('click', function(e){
        $.ajax({
          url:  url,
          type: 'POST',
          async: false,
          dataType: 'json',
          enctype: 'multipart/form-data',
          cache: false,
          success: function(data){
    
          },
          error: function(){}
        });
    });
    
    0 讨论(0)
  • 2020-12-05 20:46

    For me I have the same problem using jsonp

    after 2 minutes without answer $ajax seem to retransmit the request...

    I suspect is a browser issue because jsonp is switched to <script... tag

    and without answer I suspect the browser restransmits the request after ~ 2 minutes...

    My workarround was done by responding anything asap and after 10 minutes my script ask for success or not...

    0 讨论(0)
  • 2020-12-05 20:50

    An alternative to disabling the button would be to use the .one() method and re-bind the event handler after callback:

    var clickHandler = function(e){
        $.ajax({
          url:  url,
          type: 'POST',
          async: true,
          dataType: 'json',
          enctype: 'multipart/form-data',
          cache: false,
          success: function(data){
            $('#button1').one('click', clickHandler);
          },
          error: function(){}
        });
        e.stopImmediatePropagation();
        return false;
    }
    
    $('#button1').one('click', clickHandler);
    
    0 讨论(0)
提交回复
热议问题