JavaScript中的getJSON和变量作用域 [英] getJSON and variable scope in javascript

查看:84
本文介绍了JavaScript中的getJSON和变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了对后端php代码进行函数调用,我们实现了一个称为ActionProxy的东西,如下所示:

In order to make function calls to our back-end php code we've implemented something called an ActionProxy like this:

function ActionProxy(action, input, callback){  
    $.post("ActionProxy.php?method="+action, 
        { data: input},   
            function(data, textStatus, XMLHttpRequest){
                        //return data.ResponseWhatever
                        }
});

我们遇到的问题是,由于变量作用域限制(我们假设),设置
var res = data.ResponseWhatever

return data.ResponseWhatever

The problem we're having is that using data outside the ActionProxy is impossible due to variable scope limitations (we assume), setting
var res = data.ResponseWhatever
or
return data.ResponseWhatever

毫无用处.如何最恰当地处理这些响应,以便调用actionproxy的函数可以访问响应值?

is pretty futile. How would one handle these responses most appropriately so that functions calling the actionproxy can access the response values?

推荐答案

您可以使用window.ResponseWhatever = data.ResponseWhatever,但这并不是最明智的选择.您想要做的是这样的事情:

You could use window.ResponseWhatever = data.ResponseWhatever, however, this is not the smartest thing to do. What you want is to do something like this:

function ActionProxy(action, input, callback){
    $.post("ActionProxy.php?method="+action, {data:input},
        function(data, textStatus, xhr){callback(data);});
}

注意:我不是jQuery专家,所以我可能错误地获得了jQuery的某些部分,但关键是要调用return data而不是callback(data);.

Note: I'm no jQuery-guru, so I might have gotten some of the jQuery-parts wrongly, but the point is that where you want to call return data you instead call callback(data);.

这篇关于JavaScript中的getJSON和变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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