I am confused with the variable scope in Javascript. I am trying to load data file (.json) using Prototype library and parse the response text using json-sans-eval. The problem is it seems to me that the content from data file is lost if I tried to access “dataObj” outside of the Ajax.Request scope.
The variable in Javascript has reference count. I don’t understand how can the global variable ‘dataObj’ will lose its data. Any hint or help?
Thank you!
var dataObj;
function OnLoadHandle() {
new Ajax.Request('data.json',
{
method:'get',
onSuccess: function(transport)
{
var response = transport.responseText || "no response text";
dataObj = jsonParse(response);
console.log(dataObj["[0,0]"]); // OK
},
onFailure: function(){ alert('Something went wrong...') }
});
console.log(dataObj["[0,0]"]); // ERROR
}
The second invocation of
console.log(...)at the end ofOnLoadHandleruns immediately, whereas the one insideonSuccessruns only after the request completes. The secondconsole.logserves no purpose.More broadly, this means that there is no point in making
dataObja global variable. It is only useful after it is assigned inonSuccessand should therefore be scoped as a local variable withinonSuccess. If you need it elsewhere,onSuccessshould pass it as a parameter to some other function.