views:

1131

answers:

2

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?

+2  A: 

Your 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
You've just helped me a great Deal. Have an upvote!
Daishiman
+1  A: 

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.

KeyboardInterrupt
synchronous requests block the browser, so in the event of a server timeout, the browser might get hung, ... indefinitely. While Synchronous requests are taking place, the page will not respond to user input.
Kent Fredric