我怎么能一个AJAX检索到的值返回到JavaScript中的当前函数的父函数?函数、我怎么能、AJAX、JavaScript

2023-09-10 13:18:07 作者:此生再无相见时

我有以下的JavaScript(和jQuery)code:

I have the following JavaScript (and jQuery) code:

function checkEmail(email) {
    if (email.length) {
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            return data;
        })
    }
}

我要匿名函数返回数据于母公司的功能, checkEmail()。我试图做这样的事情:

I want the anonymous function to return data to the parent function, checkEmail(). I tried doing something like this:

function checkEmail(email) {
    if (email.length) {
        var ret = null;
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            ret = data;
        })
        return ret;
    }
}

但当然,这是行不通的,因为 $。的getJSON()调用是异步的,所以它会返回RET GET请求完成之前。

But of course this won't work because the $.getJSON() call is asynchronous, so it will return ret before the GET request is finished.

在这里有什么想法?

感谢您!

推荐答案

一般情况下,来处理此类问题的最佳方法是使用某种形式的回调函数。其实,这真的是唯一可行的解​​决方案 - 唯一的其他选择是编写您自己的扩展到浏览器,这是一个有点多(除非你真的很喜欢撞你的头靠在墙上)。实际上有相当多的这些主板平行的问题:你可以尝试寻找一些,很多都是很不错的。

Generally, the best way to handle this type of issue is to use some form of callback function. Actually, it is really the only practicable solution -- the only other option is coding your own extensions to the browser, and that is a little much (unless you really like banging your head against a wall). There are actually quite a few parallel questions on these boards: you might try searching for some, many are very good.

修改您的code:

function checkEmail(email) {
    /*
        original parts of the function here!
    */

    if (email.length) {
        $.getJSON('ajax/validate', {email: email}, function(data){
            if (data == false) {
                // stuff
            }
            checkEmailResponse( data );
        })
    }
}

function checkEmailResponse( data )
{
    // do something with the data.
}