Jquery表单验证ajax

时间:2016-09-05 15:08:54

标签: javascript php ajax forms

我遇到多个ajax提交问题。每当我点击按钮提交每次点击都会再调用一次ajax POST。

代码吼叫

submitHandler: function(form,event) {
            //show popup phonenumber check
            //check captcha on server side
            var fm = $(form);
            $(fm).unbind('submit').submit();
            $("#registration_phone_check").fadeIn();
            var country_number = $("#myDropdown")[0].innerText+fm[0].elements['phone'].value;
            country_number = country_number.replace(/(\r\n|\n|\r)/gm,"");//delete all break lines in string
            $("#phone_check").val(country_number);
            //send code
            $("#check_phone_send_code").click(function(e){
                e.preventDefault();
                var language = "en";

              $("#phone_confirmations").fadeIn();
                    ajax.post('/'+language+'/registration', {
                        email:fm[0].elements['email'].value,
                        uname:fm[0].elements['uname'].value,
                        surname:fm[0].elements['surname'].value,
                        birthday:fm[0].elements['birthday'].value,
                        password:fm[0].elements['password'].value,
                        phone:$("#phone_check").val(),
                        grecaptcha_response:grecaptcha.getResponse()
                    }).done(function(resp) {
                //code when ajax success or some error is returned
                    }).fail(function(resp){
                        grecaptcha.reset();
                    });
                });
        },

所以问题是,如果没有多个ajax POST请求,我怎么能只发送一次ajax。

1 个答案:

答案 0 :(得分:0)

一种方法是定义一个锁定或解锁后发请求的全局变量。这样的事情:

var submitting = false;

...

$("#check_phone_send_code").click(function(e){
   if(submitting == false){// check locking variable
     submitting = true; // lock posts
     ajax.post('/'+language+'/registration', {
                    email:fm[0].elements['email'].value,
                    uname:fm[0].elements['uname'].value,
                    surname:fm[0].elements['surname'].value,
                    birthday:fm[0].elements['birthday'].value,
                    password:fm[0].elements['password'].value,
                    phone:$("#phone_check").val(),
                    grecaptcha_response:grecaptcha.getResponse()
                }).done(function(resp) {
                   submitting = false; // unlock posts
            //code when ajax success or some error is returned
                }).fail(function(resp){
                    submitting = false;  // unlock posts
                    grecaptcha.reset();
                });

   }
}