I’m building a simple aggregator-type app that would pull in data from multiple websites (via their APIs) and then present the data on the same page. For example, on a search for John Grisham, the app would get data from his page from Wikipedia, his highest rated book from Goodreads and his author page from IMDb (and so on).
Right now I have the jQuery code for requesting and parsing the JSON response from these APIs separately, and then update the page using the $.when/$.done functions.
I’m trying to create a single function that would handle the AJAX requests, instead of having 5-6 different separate ones. But since each of these sites has a different API implementation for requesting and returning data, I can’t make a catch-all function.
My approach so far has been somewhere in the middle – I create an object with the required parameters and response-parsing function like so:
var Search = {
wikipedia: {
url: 'http://en.wikipedia.org/w/api.php?redirects&callback=?',
param: {
page: searchQuery,
prop: 'text',
action: 'parse',
section: 0
},
template: function(response) {
$('#wikipedia').html(response.parse.text['*']);
}
},
imdb: {
url: 'http://www.imdbapi.com/?callback=?',
param: {
t: searchQuery
},
template: function(response) {
$('#imdb').html(response.Plot);
}
}
};
…and then loop through it to execute all the searches asynchronously, and on success execute the template method.
for (var eachSite in Search) {
function searchDo (site) {
$.ajax({
url: site.url,
data: site.param,
dataType: 'json',
success: site.template
});
};
searchDo(Search[eachSite]);
}
This is the part I can’t quite wrap my head around. Although it works, it doesn’t seem quite right. Potentially the list of APIs to access would include around 10-15 sites.
Is there a better way of doing what I’m trying to accomplish here?
If you want to use $.when you could assign each request to a variable, push that variable into an array then use the array as arguments for $.when