getJSON and variable scope in javascript
In order to make function calls to our back-end php code we've implemented something call开发者_StackOverflow社区ed an ActionProxy like this:
function ActionProxy(action, input, callback){
$.post("ActionProxy.php?method="+action,
{ data: input},
function(data, textStatus, XMLHttpRequest){
//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
is pretty futile. How would one handle these responses most appropriately so that functions calling the actionproxy can access the response values?
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);});
}
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);
.
Well, I did sorta the solution provided by Alxandr. It turns out if I want the result, I'll have to implement a callback, but in order to not care about the result I just call the ActionProxy with the first two arguments and check if the callback function is present like so:
function ActionProxy(action, input, callback){
$.post("ActionProxy.php?method="+action, {data:input},
function(data, textStatus, xhr){
if(callback){
callback(data);
}
});
}
I would've expected an error calling a three-argument function with two arguments. Oh well - javascript is a strange language. :)
精彩评论