【发布时间】:2015-08-25 05:26:04
【问题描述】:
我的应用程序有一个通用的验证方法validateFields。该脚本将检查需要针对多个条件进行验证的每个字段并增加计数器。
if(validate_for_nil(field) == true){
// return true and continue other validations
} else {
//stop further actions and raise error
}
if(validate_max_chars(field) == true){
//continue other validations
}else{
//stop and raise error
}
同样对于唯一性验证,我需要发送一个 ajax 请求。但问题是,我的函数没有等待 ajax 响应。它将检查条件 undefined 作为 ajax 响应。如何让我的整个函数等待 ajax 响应到来? ajax 请求中的 Async:false 对我来说不方便。请帮忙 这是我的代码:
function form_validation() {
$("[data-required=true]:visible").each(function(){
element = $(this);
errors = validate_fields(element);
total_errors = total_errors + errors;
})
if(total_errors == 0) {
//submit form
}else{
//do nothing
}
}
function validate_fields(field) {
error = 0
if(validate_for_nil(field) == true){
// return true and continue other validations
} else {
error = error+1
raise_error()
}
if(validate_max_chars(field) == true){
//continue other validations
}else{
//counter increment and raise error
}
if(validate_uniqueness(field) == true) { // this method calls an AJAX request
// return true
}else {
// counter increment and raise error
}
}
【问题讨论】:
-
使用 .deferred / deffered object
标签: jquery ajax validation