I'm writing a web application and need to initialize some parameters that I'm pulling via the $.getJSON() method.
$.getJSON("../config/", function(data)
{
console.debug(data);
}
Now since these values will be used globally throughout the script and will not be triggering an event directly (which is the only implementation of $.getJSON() I could find in the documentation), how can I returning or retrieve this callback data?
I'm writing a web application and need to initialize some parameters that I'm pulling via the $.getJSON() method.
$.getJSON("../config/", function(data)
{
console.debug(data);
}
Now since these values will be used globally throughout the script and will not be triggering an event directly (which is the only implementation of $.getJSON() I could find in the documentation), how can I returning or retrieve this callback data?
Share Improve this question edited Dec 1, 2011 at 21:17 Lightness Races in Orbit 385k77 gold badges664 silver badges1.1k bronze badges asked Jul 12, 2009 at 1:20 KeyboardInterruptKeyboardInterrupt 3,7638 gold badges37 silver badges41 bronze badges 2- 1 I don't get your problem here, $.getJSON 2nd argument is a callback function, which is called once the request is complete and successful. – Luca Matteis Commented Jul 12, 2009 at 1:52
- What do you want to do with the data from getJSON? – txwikinger Commented Jul 12, 2009 at 2:50
2 Answers
Reset to default 17Your best bet is to stick with the callback technique.
There are 2 real ways to make it work, both are essentially the same.
$.getJSON("../config/", function(data) {
SomeObject.config = data;
SomeObject.load(); # assuming load tells some-object that it now has data and to get cracking
});
or
$.getJSON("../config/", function(data) {
SomeObject.load( data ); # SomeObject sets itself up and starts doing its thing
});
Trying to use $.getJSON in a synchronous way ( ie: having it return a value ) will only end in tears and misery for both you and the people using your site, because Synchronous connections have a tendency to block the entire UI. :)
As it stands, doing anything like this asynchronously
var i = null; #1
$.getJSON("../config/", function(data) { #2
i = data; #3
}); #4
some_function_with(i); #5
Will not work, because line 5 is almost guaranteed to execute before line 3.
Kent Fredric: I'm not sure if your approach might be better, so if your method is better let me know how and I'll accept your solution over my own, but this is how I did it:
var my_data = null;
$.ajax(
{
url: "../config/",
dataType: "json",
async: false,
success: function(data)
{
my_data = data;
}
});
Also thank you RichieHindle, I didn't know it was possible to replace variables outside of functions without return.