dpfw3607 2010-11-10 10:41
浏览 24
已采纳

为什么这个函数返回“undefined”? [重复]

This question already has an answer here:

I have a form-validation function which validates and also checks to see if the username is taken or not (ajax).

This is how I call the code:

 function validate(){
   if(usernameValid()){
      return true;
   }
   else {
      return false;
   }

 }

I also alert the function in order to see what it returns:

  alert(usernameValid());

The problem is that the alertbox alerts "Undefined" in some cases, so my validation wont jump to the next field, it hangs. To be more specific, it alerts "Undefined" in all cases except when the "length===0", then it alerts false which is correct.

Here is the usernameValid function:

    function usernameValid(fld) {
     if( $('#username').val().length !== 0 ) {
      $.post("username_check.php", {
        username: $('#username').val()
      }, function(response){
            response = escape(response);

            if(response==1){
             $('#username_error_invalid').show();
             $('#username_error_empty').hide();
             $('#username_error_taken').hide();
             return false;
            }
            else if(response==2){
                 $('#username_error_taken').show();
                  $('#username_error_invalid').hide();
                 $('#username_error_empty').hide();
                 return false;
            }
            else {
                 $('#username_error_taken').hide();
                  $('#username_error_invalid').hide();
                 $('#username_error_empty').hide();
                 return true;
            }
      });
     } 
     else{ 
         $('#username_error_empty').show();
         $('#username_error_invalid').hide();
         $('#username_error_taken').hide();
         return false;
     }
}

Anybody know what is wrong, ie why the code returns undefined in the cases where I test the "response" variable?

BTW: The validation itself for the username works (error is displayed when it should etc), but it returns undefined...

Thanks

</div>
  • 写回答

1条回答 默认 最新

  • ds342222 2010-11-10 10:46
    关注

    This is an asynchronous call:

    $.post("username_check.php", {....
    

    So the return statements in the callback happen long after usernameValid returns (and since it didn't return anything when it was run, it's undefined).

    Where you have return false; you should call another function, for example: userNameInvalidFunction(), and something else for true...or just continue submitting, etc.

    The alternative is to make your AJAX call synchronous...but I strongly recommend against this, since it'll completely lock up the user's browser while it executes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?