我怎么能一个AJAX检索到的值返回到JavaScript中的当前函数的父函数? [英] How can I return an AJAX-retrieved value to the parent function of the current function in JavaScript?

查看:117
本文介绍了我怎么能一个AJAX检索到的值返回到JavaScript中的当前函数的父函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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.
}

这篇关于我怎么能一个AJAX检索到的值返回到JavaScript中的当前函数的父函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆