Hey all. I have, what appears to be, a trivial problem. I have the following JavaScript:
$(function() {
var r = GetResults();
for(var i = 0; i <
move your "do stuff with r" block into your $.getJSON callback. you can't do stuff with r until it has been delivered, and the first opportunity you'll have to use r is in the callback... so do it then.
$(function() {
var r = GetResults();
});
function GetResults() {
$.getJSON("/controller/method/", null, function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
return data;
});
}
Given your updated requirements ...
I cannot move the for loop processing into the callback function of the JSON request because I am reusing the functionality of GetResults several time throughout the page, unless I want to duplicate the code. Any ideas?
... you could modify GetResults()
to accept a function as a parameter, which you would then execute as your $.getJSON
callback (air code warning):
$(function() {
GetResults(function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
});
});
function GetResults(callback) {
$.getJSON("/controller/method/", null, callback);
}
As you can see from the general tide of answers, you're best off not trying to fight the asynchronous jQuery programming model. :)
Move the data processing into the callback:
$(function() {
GetResults();
});
function GetResults() {
$.getJSON("/controller/method/", null, function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
});
}