首页 > 通过ajax提交表单,点击按钮一次,ajax提交多次是什么原因?

通过ajax提交表单,点击按钮一次,ajax提交多次是什么原因?

通过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');
    }
});

type为button和submit的input按钮点击时候会提交表单,再加上你写的事件应该就是会重复,要不你把input[type=button]换成div试试?


按你这种写法,当然会提交多次。没人说点击事件只能执行一次。两种办法,一是把on改成one,使得点击提交事件只发生一次;二是点击之后把按钮button禁用(disabled属性),或者移除button上绑定的事件(off方法)。


做好防重复提交就好了。
在form内, 点击button默认也是会提交表单的,不过默认的提交方式不是ajax。你绑定在button上的事件是以ajax提交表单数据,所以可以看看是重复的请求是什么类型的;
如果一个是ajax请求, 一个不是,则就应该是点击button的时候,默认行为和自定义行为都发生了。
如果两个都是ajax请求,则可能是button被连续点击了多次。
通用的方式是:

【热门文章】
【热门文章】