提交带有onSubmit的表单 [英] Submitting a form with an onSubmit

查看:128
本文介绍了提交带有onSubmit的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单onSubmit正在呼叫:

onsubmit="validate(this); return false;"

validate();如下:

function validate(obj) {
    $.ajax({
        url : "ajax/validate_check.php",
        type : "POST",
        data : $("#" + obj.id).serialize(),
        success : function(data) {
            $('#' + obj.id + ' :input.form_errors').removeClass('form_errors')
            data = $.parseJSON(data);
            if(data['error_count'] >= 1) {
                $.each(data, function(i, item) {
                    $('#' + i).addClass('form_errors');
                });
            } else {
                $('#' + obj.id).submit();
            }
        }
    });
}

当我遇到0错误时,它正在尝试提交表单,但出现了无限循环.我意识到它正在发生,因为我的onSubmit再次调用了该函数.准备好后,我该如何实际提交表格?

When I have 0 errors it's trying to submit the form but I'm getting an infinite loop. I realize it's happening because my onSubmit calls the function again. How do I actually submit the form when I'm ready?

我正在寻找解决此问题的最佳方法.我想验证onSubmit以快速响应用户,然后我想以我知道数据去向的方式实际提交表单(例如register.php将注册用户).

I'm just looking for the best way to approach this. I want to validate onSubmit for a quick response to the user and then I want to actually submit the form that way I know where the data is going (eg register.php will register a user).

这就是为什么我不执行合并的动作/验证脚本的原因,因为我不知道我要提交的表单.我可能需要重新调整我的操作方式.

That's why I'm not doing a combined action/validate script because I wouldn't know which form I'm submitting. I probably need to rearrange the way I'm doing this.

推荐答案

删除onsubmit="validate(this); return false;"

并使用以下功能:

$('form').submit(function(e){
    e.preventDefault();
    var $form = $(this),
        $formId = $form.attr('id'),
        $formName = $form.attr('name');

    $.ajax({
        url : "ajax/validate_check.php",
        type : "POST",
        data : $("#" + $formId).serialize(),
        success : function(data) {
            $('#' + $formId + ' :input.form_errors').removeClass('form_errors')
            data = $.parseJSON(data);
            if(data['error_count'] >= 1) {
                $.each(data, function(i, item) {
                    $('#' + i).addClass('form_errors');
                });
            } else {
                document.forms[$formName].submit();
            }
        }
    });
});

提琴,您可以在其中使用表格idname进行测试: http://jsfiddle.net/67rvg/3/

Fiddle where you can test with form id or name: http://jsfiddle.net/67rvg/3/

这篇关于提交带有onSubmit的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆