提交带有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();
}
}
});
});
提琴,您可以在其中使用表格id
或name
进行测试: http://jsfiddle.net/67rvg/3/
Fiddle where you can test with form id
or name
: http://jsfiddle.net/67rvg/3/