AJAX存储了请求和表单提交

时间:2013-10-24 15:55:02

标签: javascript php jquery ajax validation

我正在开发一个jQuery验证“插件”(还不是一个插件),它使用我的Zend_Form验证器在提交之前验证字段,客户端,所以我只需要指定一次我的约束而不是两个(Zend Validators + jQuery Validate Plugin,例如)。

我为每个字段存储验证AJAX请求,然后等待它们完成,然后读取结果并显示或不显示错误消息。

问题:当我输入经过验证的字符串并点击提交时,它显示没有错误(目前为止很好),但我必须重新点击提交按钮表单才能真正提交。< / p>

return true函数中使false.whenAll被忽略并且不起作用,这就是为什么我使用一个标志告诉函数是否可以真正提交形式。

$(function() {

    var form = $('form'); // target form
    var requests = [], validations = []; // used to store async requests and their results
    var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs we want to check in the form
    var cancelSubmit = true; // skip validation flag

    form.submit(function( ) {

        // if we call the submit inside the function, skip validation and do submit the form
        if(cancelSubmit === false) {
            console.log('[-] cancelSubmit is false. Validation skipped.');
            this.submit();
            return true;
        }

        console.log('[-] Entering validation');

        // resetting requests and validations
        requests.length = 0;
        validations.length = 0;

        // for each input (text/password), storing the validation request
        $('input[type="text"], input[type="password"]').each(function(i) {

            var validatorField = $(this).attr('data-validator');
            var valueField = $(this).val();

            postData = {
                validator: validatorField,
                value: valueField
            };

            // storing requests into an array
            requests.push($.post('/validate', postData));
        });

        (function($) {
            $.whenAll = function() {
                return $.when.apply($, arguments);
            };
        })(jQuery);

        // when all the requests are done and returned a response
        $.whenAll(requests).then(function() {

            // show the validation status for each input
            $.each(requests, function(i, element) {
                element.done(function(data) {

                    // response is formatted like this
                    // { valid: 1 } or { valid: 0, message:"This is the error message" }
                    json = $.parseJSON(data);
                    formGroup = $('input:eq('+i+')').parent();

                    // if it isn't valid, show error and store result
                    if(json.valid == 0) {
                        if($('span.help-block', formGroup).length == 0) {
                            $(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
                            $('label', formGroup).addClass('control-label');
                        }

                        validations.push(0);
                    }
                    // else, remove error (if there was) and store the result
                    else if(json.valid == 1) {

                        if($(formGroup).hasClass('has-error'))
                        {
                            $(formGroup).removeClass('has-error');
                            $('.help-block', formGroup).remove();
                        }

                        validations.push(1);
                    }

                    // if we got all the validations required
                    if(validations.length == nbInputs)
                    {
                        console.log('[-] All validations have been done.');

                        // and if no error ("0") in the results, we resubmit the form with skip-flag
                        if($.inArray(0, validations) == -1){
                            console.log('[-] No errors. Submitting form.');
                            cancelSubmit = false;
                            form.off('submit');
                            form.submit();
                        }
                        else
                            console.log('[-] There is still errors.');
                    }
                });
            });
        });

        // there are errors, so we won't submit the form
        if(cancelSubmit === true)
            return false;
    });
});

你看到我的代码存在逻辑缺陷吗?也许用标志重新提交表单不是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

您将从子范围返回,而不是从表单提交处理程序返回。相反,请始终阻止提交,然后在您希望提交时强制提交form[0].submit()

form.submit(function(e) {
    e.preventDefault();
    ...

    // now i want to submit...
    form[0].submit();

form[0].submit()将绕过你的jquery绑定提交处理程序。