JavaScript函数总是运行底层代码

JavaScript function always run bottom code

本文关键字:代码 运行 函数 JavaScript      更新时间:2023-10-31

我有这个部分工作的代码。它想做的是检查数据库中现有的电子邮件地址。如果不存在电子邮件,则return true;

 $(document).ready(function() {
    var email_check = 0;    
        var checking_html = '<img src="http://i.imgur.com/Y8wXAZp.gif" /> Checking...';
        var characters_error = 'Minimum amount of chars is 6';
        //when button is clicked
        $('.register').click(function(){    
            //run the character number check
            if($('#email').val().length < 1){
                $('#email_result').html(characters_error);
                return false;
            }                   
            else{           
                //else show the cheking_text and run the function to check
                $('#email_result').html(checking_html);
                alert(check_email_availability());
            }
        });

  });
//function to check email availability  
function check_email_availability(){
        //get the email
        var email = $('#email').val();
        //use ajax to run the check
        $.post("check_email.php", { email: email },
            function(result){
                email_check = 0;
                //if the result is 1
                if(result == 1){
                    //show that the email is available
                    email_check = 1;
                }else{
                 email_check = 0;
                }
        });
        if (email_check == 1){  
             return true;   
        }else{
             return false;      
        }   
}  

现在,问题是,如果当前状态是false,当我输入数据库中不可用的电子邮件并单击按钮时,我仍然会收到false警报,而当我下次单击按钮时我会收到true警报。出于某种原因,函数首先执行底部代码(检查email_check值),然后执行函数。为什么?我的代码出了什么问题?如何让它执行函数,然后检查email_check值,无论是否为1

我会改变这一点,在您的检查函数上设置一个ajax成功回调,类似于。

success: function (data, status, xhr ) {
   myFunctionShowEmailSuccess();
},
error: function (xhr, status, error) {
    myFunctionShowEmailFailure();
}

尝试这样做。

//function to check email availability  
function check_email_availability(){
        //get the email
        var email = $('#email').val();
        //use ajax to run the check
        $.post("check_email.php", { email: email },
            function(result){
                email_check = 0;
                //if the result is 1
                if(result == 1){
                    //show that the email is available
                    return true;
                }else{
                 return false;
                }
        });
}