0

我正在使用下面的 ajax 函数检查输入的登录名是否已在我的数据库中注册...

function freelog(login) {
    var data = {login:login};
    $.post ('freelog.php', data, function(response){
            if(response == '1') {
                freelogin = true;
            } else if(response == '0') {
                freelogin = false;
            } else {
                freelogin =  response;
            }
    });
    return freelogin;
}

当然,我的线路有问题:

return freelogin;

原因是 $.post 需要一些时间来回答......我不知道如何解决这个问题......希望你能帮助我:)

4

2 回答 2

4

你不能让你的“freelog()”函数返回一个值,正如你所想的那样,所以让它接受第二个参数。这应该是响应可用时调用的函数。

function freelog(login, callback) {
    var data = {login:login};
    $.post ('freelog.php', data, function(response){
            if(response == '1') {
                freelogin = true;
            } else if(response == '0') {
                freelogin = false;
            } else {
                freelogin =  response;
            }
            callback( freelogin );
    });
}

JavaScript 浏览器环境的异步特性倾向于将所有 API 都推向这种形式。

编辑——调用你的函数,然后,看起来像:

  freelog( username, function( isOk ) {
    if ( isOk ) {
      // put a big green check mark next to the username field
    }
    else {
      alert("That user name is taken");
    }
  }

管他呢。

于 2012-05-26T13:16:34.447 回答
0

Ajax is such a pain, in that the benefits of asynchronocity also has it's drawback (at least until we think of it as the norm).

You need to return the result in the callback, not just set the variable, which, as you discovered, has no value since the ajax is still being tended to. Here's one example of how to change your code easily:

function freelog(login) {
    var data = {login:login};
    $.post ('freelog.php', data, function(response){
            if(response == '1') {
                freelogin = true;
            } else if(response == '0') {
                freelogin = false;
            } else {
                freelogin =  response;
            }
            return freelogin;
    });
}

All I did was move the return to within the post callback, so it won't get returned until the request is done. As advised by others, it is better to get more sophisticated and have things like:

  1. A spinner or "checking" or some kind of feedback, assuming the request takes longer than a millisecond.

  2. Having the freelogin actually return something meaningful. Assuming it's being called by another function that is awaiting the response to output "Not available" you should be fine, but if you are just outputting the freelogin or have some code that depends right away on the response, you'll need to further revamp to get your script asynchronous.

Last bit of advice, here's a nice way to tighten up that callback function:

$.post ('freelog.php', data, function(response){
            return (Number(response) <= 1) ? Boolean(Number(response)) : response;
    });
于 2012-05-26T13:54:52.900 回答