开发者

jQuery $.post not completing when called

I have the following function which I use to check whether or not an email address is already registered.

checkTaken() {
  var email_var = $('input#email').val();

  $.post("../includes/check_email.inc.php",{email:email_var} ,function(data) {
      var ret = data + "";
    if(ret=="true") {//if username not avaiable
      $('div#emailTaken').show();
      $('input#email').addClass('redBack');
      return false;
    } else {
      $('div#emai开发者_如何学GolTaken').hide();
      $('input#email').removeClass('redBack');
      return true;
    }
  });
} 

When I call it using something like the following it works fine:

email.blur(checkTaken);

But when I do something like

var test1 = checkTaken();

or

if(chekTaken) {

something quirky happens. It enters the function, executes the $.post line, but then never enters the rest of the routine. Why is this? And how do I fix it?

As a note, when I call the function using the last two examples, I do get information back from the server as seen through firebug.If I add a watch for test1, it remains undefined.


You are mixing Async post callback with sync function call. Return from callback will not return to the callee.


That is happening because checkTaken() does not wait for the $.post to finish before returning, due to the fact that $.post will fire off an asynchronous request to the server. What you can do is use $.ajax instead and set the async option to false (bearing in mind that it will block the browser momentarily while it waits for the request completes).


The reason is that the first A in AJAX means "asynchronous". This means that your code continues executing before the HTTP request is complete. When the request is complete, your handler function is run. You therefore have to structure your code to take account of this. This generally means placing all the code dependant on an AJAX request in your handler functions, as you already have done to some extent.

$.post("../includes/check_email.inc.php",{email:email_var} ,function(data) {
    var ret = data + "";
    if(ret=="true") {//if username not avaiable
        $('div#emailTaken').show(); // this works
        $('input#email').addClass('redBack'); // this works

        return false; // this does nothing
    } else {
        $('div#emailTaken').hide(); // this works
        $('input#email').removeClass('redBack'); // this works

        return true; // this does nothing
    }
});


it's because your return statement is in the $.post request and not in the function. Isn't the same thing.

Your function doesn't return any value, that's why you don't enter in your other piece of code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜