views:

162

answers:

2

Can I do this ?

var global = 0;

var truc = $.getJSON("events.json", function(json){
 //alert("JSON Data: " + json[0].titre);
  global = json;
});

I want to keep the contents of json and work with it outside the function. If it was C, I would just keep the pointer but I don't know what to do with JS

+2  A: 

yes you can do that

Scott Evernden
I wish it would work. Guess what, If I put alert(json) at the end of my code, it displays zero !
toto
I meant alert(global) of course -.-
toto
immediately after? of course it failed. the request hasn't finished yet. the variable `global` won't have a new value until the request completes
Jonathan Fingland
That's true, this is a callback function after all. Alright just give me a minute then.
toto
A: 

I don't know the details on how json works, so I cannot say what happens in your case, but this simple test works as a simplified example on how your global variable will actually work:

var global = 0;

function callTest(arr) {
    //alert("JSON Data: " + json[0].titre);
    global = arr;
}

var array = new Array("w", "q");
callTest(array);
alert(global);

This means that it has something to do with how json works. One thing: Are you sure the function initialized with json is actually run before you test with alert(global) ?

awe
It wasn't. There's a 30 ms lag waiting for my server to send the JSON.What I did is that all the code that needs this JSON will start from the callback.
toto