Can anyone see the problem with this code? When ‘out’ is returned, it has a value of “”. I have no idea why, perhaps it’s something about the getJSON function im not aware of.
I’m trying to pass a URL to this function, have it perform getJSON on the URL, and add the results (which i’m also formatting) to a text string. I want them all in one text string, so i can parse the string with regex. Any help is appreciated, thanks!
function getSearch(url) {
var out = ''; // output variable
$.getJSON(url, function(data) {
for(var i = 0; i < numResults; i++) {
out += '<p class="hash_list">' + '<a href="http://www.twitter.com/' + data.results[i].from_user + '">' + data.results[i].from_user + '</a>: ' + data.results[i].text + '</p>';
}
});
return out;
}
ajax is asynchronous, the code you have would return before the ajax request has finished.
There are a few ways you can restructure your code.
You can pass in a callback function that gets executed once the request has finished.
Then you would use the function like this.
Or you can use jquery deferreds to return a promise and pass the out variable as part of the argument when you resolve the deferred. Here’s an example