1

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 
}
1
  • 5
    It's not about scope, the issues is that _A_jax is _A_synchronous, the second console.log is being executed before the request completes... Commented Aug 7, 2011 at 1:12

1 Answer 1

6

The second invocation of console.log(...) at the end of OnLoadHandle runs immediately, whereas the one inside onSuccess runs only after the request completes. The second console.log serves no purpose.

More broadly, this means that there is no point in making dataObj a global variable. It is only useful after it is assigned in onSuccess and should therefore be scoped as a local variable within onSuccess. If you need it elsewhere, onSuccess should pass it as a parameter to some other function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.