I need to make this data
variable global:
$.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 to have this globally declared. Do I need to declare it as array?
ThiefMaster
320k85 gold badges607 silver badges648 bronze badges
asked Jul 1, 2012 at 16:29
2 Answers 2
Any variable can be "made global" by attaching it as a property of the window.
window.data = data;
You can now access data
as a global variable.
answered Jul 1, 2012 at 16:30
Sign up to request clarification or add additional context in comments.
5 Comments
Nimphious
Also useful is
self
in case you don't have access to the DOM, such as from a Web Worker.user123_456
And where do I put that? outside the ajax scope? I tried that but It says that
data
is not definedNiet the Dark Absol
Put it wherever the original
data
variable is.user123_456
can you please give me an example on my posted question. As I have tried and it is not working. I want to use this data variable as in global scope. Please help
Niet the Dark Absol
Inside the
success
function, since that's where data
is defined.Set a variable equal to what you wish data
to be equal to. And when giving data
its value, reference the variable. Like this:
var obj = {};
$.ajax({
// ....
data: obj,
// ....
});
answered Jul 1, 2012 at 16:32
Comments
lang-js