简体   繁体   中英

Modify global javascript variable inside a function

I'm trying clone a json object inside a function wanting to access the object outside the function. But when function is done, the object still seems to be undefined. Seems like it's not the same variable?

var jsonUserObj;
$.getJSON("user.json", function(content){
    jsonUserObj = $.parseJSON(JSON.stringify(content));
    console.log(content);
    console.log(jsonUserObj); //looks fine!
});
console.log(jsonUserObj); //undefined

inside the callback function it contains all the data, but it does not remain outside of it. How to make it assessible globally?

$.getJSON is asynchronous so console.log at the end of your code runs before $.getJSON returns its result.

You should modify the variable inside the callback (where it looks fine ) and then use the variable inside that function, this callback is the only place where you can guarantee your variable is set.

You could also use the synchronous version of $.ajax but that's really not recommended (and probably unnecessary).

You got a typo:

console.log(jsonUserObject);

It should be

console.log(jsonUserObj);

You need to declare var jsonUserObj outside a function.

Also it looks like you have a typeo, is it jsonUserObj or jsonUserObject?

Could it be a question of timing? If that getJSON method is firing asynchronously then it may not have returned it's value by the time you have fired the last line. Does that make sense?

$.getJSON performs an ajax call, which is asynchronous. The code after it will continue evaluating while it waits for a response. When the response comes back, the program flow will jump back into the success/error/complete handlers of the ajax call.

tldr: Anything you do with data from an ajax call must be in the success handler of that ajax call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM