在ajax中无法返回true

时间:2013-10-04 12:20:25

标签: ajax validation return-value

我正在创建表单验证并检查电子邮件地址(如果存在)返回true或false然后验证其他字段但它不返回true,因此我无法自动验证其他字段或提交表单验证不完成这里的代码

function check_regemail(){
var email = $("#regemail").val();
if((email.length < 6) ||
(email.indexOf('@',0) < 1) ||
(email.lastIndexOf('@') != email.indexOf('@',0)) ||
(email.lastIndexOf('@') > (email.length - 5)) ||
(email.lastIndexOf('.') > (email.length - 3)) ||
(email.lastIndexOf('.') < (email.length - 4)) ||
(email.indexOf('..',0) > -1) ||
(email.indexOf('@.',0) > -1) ||
(email.indexOf('.@',0) > -1) ||
(email.indexOf(',',0) > -1)){
$("#regemail").css("border","1px solid #F00");
return false;
}
else{
    var ajax = false;
ajax = new XMLHttpRequest();
ajax.open("GET","checkmail.php?email="+email);
ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var response = ajax.responseText;
        if(response.indexOf('exists') !== -1){
            $("#regemail").css("border","1px solid #F00");  
            return false;   
        }
        else{
            $("#regemail").css("border","1px solid #ccc");
            return true;    
        }
    }
}
ajax.send(null);            
}
}


function validate_reg(){
$.each($('form#myform :input'),function(){
$(this).blur().change();
});
if(!check_regemail() || !check_user() || !check_regpass() || !confirm_pass() ||  !check_country() ){
return false;
}
else{
return true
}
}

当我点击提交时,所有字段都应该被验证但是没有发生,并且提交表单不起作用,因为所有字段都有正确的数据

1 个答案:

答案 0 :(得分:1)

此问题是因为脚本不等待ajax完成。我建议重写代码以验证ajax成功回调中的其他字段:

if(ajax.readyState == 4 && ajax.status == 200){
    var response = ajax.responseText;
    if(response.indexOf('exists') !== -1) {
        //email fails, so no need to validate other fields
        $("#regemail").css("border","1px solid #F00");  
    } else {
        //email passes, so validate other fields
        $("#regemail").css("border","1px solid #ccc");

        //validate other fields
        if(!check_user() || !check_regpass() || !confirm_pass() ||  !check_country()) {
           //handle code when validation fails
        } else {
           //code if validation passes
        }
    }
}