$.getJSON and all the AJAX functions are asynchronous; the function returns before it gets any result. That's why there's a callback function: it gets called when the data are available. So when you write load_comments(); $.each(_json.comments, function(comment) { load_comments() just sets up the AJAX call and returns, so the each starts with _json not yet initialized. You can get around it by using asynch: false in a $.ajax call (see the documentation), but that's not the ideal solution. Better to put your $.each into the callback function: $.getJSON(paths.get_comment, _params, function(data) { $.each (data.comments, function (comment){...}) });
Danny On Jan 16, 1:17 am, Niels <[EMAIL PROTECTED]> wrote: > Is there any way to put a return from within a callback into a global > variable? I'm trying to retrieve JSON-values in one statement, and > output them in another statement; and code looks like this: > > var _json; > > function load_comments(id, params) { > if (typeof id != 'number' && typeof id == 'object' && params == null) > { > // Only the params were specified. > _params = process_params(id); > > $.getJSON(paths.get_comment, _params, function(data) { _json > = data; > return _json; }); > console.info('1 : $.getJSON(' + paths.get_comment + ', ' + > _params + > ')'); > } > > } > > function display_comments() { > load_comments(); > $.each(_json.comments, function(comment) { > $("#recent-comments-list").append("<li>" + comment.content + > "</ > li>"); > }); > > } > > Unfortunately, _json seems to remain undefined... What am I doing > wrong? Or is there really no way to accomplish this? > > Thanks a lot! > Niels