1

我一直在研究 JavaScript 验证器,但由于某种原因,即使它通过了验证,evalid 也总是返回为假……这是一个错误,好像 evalid 为假,表单不提交。

function signup_validate()
    {
        document.getElementById("email_error").innerHTML = "";
        document.getElementById("password_error").innerHTML = "";
        evalid = false;
        pvalid = false;
        email = null;
        pass = null;
        confpass = null;
        email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
        atpos=email.indexOf("@");
        dotpos=email.lastIndexOf(".");
        pass=document.forms["signup_form"]["pass"].value;
        confpass=document.forms["signup_form"]["confpass"].value;
            if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
            {
                document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
            }
            else
            {
                $.post('/resources/forms/signup.php',{email: email}, function(data){
                    if(data.exists){
                        document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
                    }
                    else
                    {
                        evalid = true;
                    }
                }, 'JSON');
            }
            if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
            {
                pvalid = true;
            }
            else
            {
                document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
            }
            alert(evalid);
            if (evalid == true && pvalid == true)
            {
                document.getElementById("signup_form").submit();
            }
            else
            {
                return false;
            }
        }

我可能错过了什么?

4

1 回答 1

3

将“evalid”设置为 true 的唯一时刻是在异步运行的函数内部。换句话说,当你设置“evalid”为真时,主函数已经结束了。

您可以尝试使用$.ajax而不是$.post使用参数async:false

尝试这样的事情:

$.ajax({
    type: 'POST',       
    url: '/resources/forms/signup.php',
    data: {email: email},
    success: function(response){
        //your function here
    },
    dataType:'JSON',
    async:false
});
于 2012-12-15T04:03:18.337 回答