getJSON and variable scope in javascript

孤街醉人 提交于 2019-12-25 04:56:17

问题


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
                        }
});

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?


回答1:


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);.




回答2:


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. :)



来源:https://stackoverflow.com/questions/2960417/getjson-and-variable-scope-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!