Javascript 如何在ajax过程完成之前创建延迟?
我有一个名为“插入注释”的按钮。当用户点击表单时,表单将被提交(使用ajax)并在数据库中插入新的注释。现在我的问题是,当用户在这个按钮上点击两次(快速),评论将被插入两次 现在我想防止再次插入,我的意思是我想在ajax进程工作时禁用所有事件。。。可能吗 这是我的密码:Javascript 如何在ajax过程完成之前创建延迟?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个名为“插入注释”的按钮。当用户点击表单时,表单将被提交(使用ajax)并在数据库中插入新的注释。现在我的问题是,当用户在这个按钮上点击两次(快速),评论将被插入两次 现在我想防止再次插入,我的意思是我想在ajax进程工作时禁用所有事件。。。可能吗 这是我的密码: $("#bottunId").click(function(){ $("#form-"+pure_id).submit(function(e){ e.preventDefault(e);
$("#bottunId").click(function(){
$("#form-"+pure_id).submit(function(e){
e.preventDefault(e);
comment(pure_id);
});
});
function comment(pure_id){
$("#textarea-"+pure_id).animate({opacity: 0.5}, 0);
var frm = $('#form-'+pure_id);
$.ajax({
url : frm.attr('action'),
type : frm.attr('method'),
data : frm.serialize(),
dataType : 'JSON',
success : function (commenting_system) {
if(commenting_system.error_msg){
$(".error_msg").html(commenting_system.error_msg); $(".error").fadeIn(200);
close_error_msg = setTimeout(function(){ $(".error").fadeOut(100); }, 5000);
$("#textarea-"+pure_id).animate({opacity: 1}, 0);
}
else{
$("#table-"+pure_id).append('<tr><td>new row</td></tr>');
$("#textarea-"+pure_id).animate({opacity: 1}, 0);
}
} // for success
}); // for ajax
} // function comment
$(“#bottunId”)。单击(函数(){
$(“#表单-”+纯id)。提交(函数(e){
e、 防止违约(e);
评论(纯id);
});
});
函数注释(纯id){
$(“#textarea-”+pure_id)。动画({opacity:0.5},0);
var frm=$('形式-'+纯id);
$.ajax({
url:frm.attr('action'),
类型:frm.attr('method'),
数据:frm.serialize(),
数据类型:“JSON”,
成功:功能(评论系统){
if(注释系统错误消息){
$(“.error\u msg”).html(注释系统.error\u msg);$(.error”).fadeIn(200);
close_error_msg=setTimeout(function(){$(“.error”).fadeOut(100);},5000);
$(“#textarea-”+pure_id)。设置动画({opacity:1},0);
}
否则{
$(“#表-”+pure_id).append('new row');
$(“#textarea-”+pure_id)。设置动画({opacity:1},0);
}
}//为了成功
});//对于ajax
}//函数注释
在ajax成功方法中,您可以删除它
$("#bottunId").removeAttr('disabled');
这应该对你有用。它在表单中设置一个名为
submitted
的标志,在刷新页面之前,该标志将阻止表单再次提交
$("#bottunId").click(function(){
$("#form-"+pure_id).submit(function(e){
if ($(this).data('submitted') !== true) {
// Mark it so that the next submit can be ignored
$(this).data('submitted', true);
// submit form
comment(pure_id);
}
e.preventDefault();
});
});
你为什么不按下按钮就把它关掉呢?如果你使用的是像bootstrap这样的框架,那就太容易了。然后在成功回调中再次启用它。将事件绑定到另一个事件中通常会导致问题。单击按钮两次,现在您有两个提交处理程序绑定。@是的,您是对的,我如何修复它?要么调用
off(“submit”)
,要么单击$(“#表单-”+pure_id).off(“submit”).on(“submit”,函数(e){…})代码>仍然插入两次。。。!谢谢,谢谢你。但是您的代码只可用一次,您需要添加$(this).data('submitted',false)
在成功
的末尾再次激活该按钮。欢迎光临。我的目的是向您展示如何禁用该按钮以防止重复评论,无论您想将其用于/之后的任何特定应用程序都由您决定:)别忘了接受解决方案,干杯。
$("#bottunId").click(function(){
$("#form-"+pure_id).submit(function(e){
if ($(this).data('submitted') !== true) {
// Mark it so that the next submit can be ignored
$(this).data('submitted', true);
// submit form
comment(pure_id);
}
e.preventDefault();
});
});