通过ajax来提交评论,有时候,点击一次按钮(type=button),ajax会重复提交多次请求,并且重复的次数也不固定,有时候会多次提交请求,有时候不会,不知道是因为使用button按钮的原因还是其他的原因?
//提交按钮,是一个<input type="button" />的类型
$form.find('#commentsubmit').on('click',function()
{
var content= $.trim(um.getContent()),
form=this.form,
quoteNumber=form.quote_number.value,
quoteName=form.quote_name.value,
hasComment=$container.find('.replycomment').length > 0 ? 1: 0;//当前是否存在评论
//console.log(content);
if(content)
{
var param={replyId:replyid,content:content,quoteNumber:quoteNumber,quoteName:quoteName,hasComment:hasComment};
//这里提交请求,有时候会多次提交
$.post('/post/newcomment',param,function(data)
{
if(data.status)
{
if(hasComment){
$container.find('.commentlist').append(data.html);
}else{
$container.prepend(data.html);
}
$self.attr('data-comments',comments+1).find('.commentsnumber').text(comments+1);
}
},'json');
}
});
做好防重复提交就好了。
在form内, 点击button默认也是会提交表单的,不过默认的提交方式不是ajax。你绑定在button上的事件是以ajax提交表单数据,所以可以看看是重复的请求是什么类型的;
如果一个是ajax请求, 一个不是,则就应该是点击button的时候,默认行为和自定义行为都发生了。
如果两个都是ajax请求,则可能是button被连续点击了多次。
通用的方式是: