How can I prevent a double submit($.post) with jQuery

偶尔善良 提交于 2019-12-10 23:30:53

问题


$(document).ready(function(){

    $("#enviar").click(function(e){

        e.preventDefault();

        //prevent run 2 or more times if the user clicks the button multiple times to send

        $.post(url,{data:data1,data2:data2},function(rp){

        });

    });

});

as prevent send 2 times the "post" if the user repeatedly click the button, without disabling the submit button


回答1:


Use a special class (e.g : submitting) as a marker to indicate the request is in progress :

$("#enviar").click(function(e){
    e.preventDefault();

    var btn = this;
    // check if already present :   
    if ( $(btn).is('.submitting') ){
        return;
    }
    // add it before request :
    $(btn).addClass('submitting');

    $.post(url,{data:data1,data2:data2},function(rp){

    }).always(function(){
        // remove it after completion or failure :
        $(btn).removeClass('submitting');
    });
});



回答2:


Use jQuery's .one event:

$("#enviar").one("click", function() {
  $.post();
});

From the docs:

Attach a handler to an event for the elements. The handler is executed at most once per element

Or if you want to do some extra checking, using on/off:

// Set up the initial bind on DOM ready
$("#enviar").on("click", doPost);

function doPost() {
  // Unbind when it is clicked
  $("#enviar").off("click", doPost);
  // Do your post
  $.post(url, {}, function() {
    // You could bind again on success if you want
    $("#enviar").on("click", doPost);
  });
}


来源:https://stackoverflow.com/questions/18723868/how-can-i-prevent-a-double-submit-post-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!