How to make javascript variable global

I need to make this data global variable:

 $.ajax({ url: "get_data.php", cache: false, dataType: 'json', data: {}, success: function(data) { for(var i = 0; i < data.results.length; i++) { if(my_data.hasOwnProperty(data.results[i].id)) { my_data[data.results[i].id].name = data.results[i].name; } } }); 

I want this to be announced globally. Do I need to declare it as an array?

+7
source share
2 answers

Any variable can be "made global" by adding it as a window property.

 window.data = data; 

Now you can access data as a global variable.

+30
source

Set the variable equal to what you want data equal. And when providing data its value, refer to the variable. Like this:

 var obj = {}; $.ajax({ // .... data: obj, // .... }); 
0
source

All Articles