简体   繁体   中英

Variable scope: Global variable inside function

I'm trying to assign a JSON array to a variable as follows:

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
});

And then calling that variable outside the function:

timeline.draw (items,options);

Using alert (items) inside the getJSON function works, however, outside of the function, it just returns 'undefined'. I thought this would work, as I declared items as a global variable in the getJSON function. What am I doing wrong?

You're probably not waiting for the getJSON function to complete. It's asynchronous which means that code under it will execute before code in the callback function.

alert(1);
$.getJSON("tljson.json",function(result){
  alert(2);
  items = JSON.stringify(result);
});
alert(3);

The example above actually alerts 1 then 3 then 2 . Note that the 3 is before the 2 .

In order to fix your code, you'll need to wait until the callback function is called so that it can assign a value to items before you try to use that variable. Coming up with a solution may depend on your situation, but an easy idea is to call some function from within your callback.

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
  doSomethingWithItems();
});

function doSomethingWithItems() {
  alert(items); // Correctly alerts items.
}

This is because your code is executing before response from getJSON is received. Use it like:

  function afterGetJSON(items) {
    timeline.draw (items,options);
  }

  $.getJSON("tljson.json",function(result){
    items = JSON.stringify(result);
    afterGetJSON(items);

  });

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