问题
$(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