JavaScript中的getJSON和变量作用域 [英] getJSON and variable scope in javascript
问题描述
为了对后端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屋!