The technology making this possible (besides the languages and TCP etc.) is JSONP. What this does is allow us to send AJAX requests to remote sites (due to security issues, browser do not allow cross domain AJAX requests. JSONP is a protocol that allows us to do so - although it has it's own issues too). Both Google as well as Twitter search support JSONP, as does jQuery - which makes querying those services from the client side very easy. Here's how to go about it.
function getGoogleContent(elem, searchtype, query) {
$.getJSON('http://ajax.googleapis.com/ajax/services/search/' + searchtype + '?v=1.0&q=' + query + '&callback=?',
function(data) {
if(data.responseData.results.length == 0)
elem.html($('').html('No results').attr('style','text-align: center; font-weight: bold; font-size: 1.2em;'));
else {
elemliststr = elem.attr('id') + '-list';
elem.html($('
elemlistobj = $('#' + elemliststr);
$.each(data.responseData.results, function(i, item) {
elemlistobj.append($('
});
elem.append($('').html($('').html('More Results').attr('href', data.responseData.cursor.moreResultsUrl).attr('target', '_blank')).attr('style', 'padding-top: 10px; font-weight: bold; text-align: center;'));
}
}
);
}
function getTwitterContent(query) {
elem = $('#twitter-tab');
$.getJSON('http://search.twitter.com/search.json?q=' + query + '&rpp=4&callback=?',
function(data) {
if(data.results.length == 0)
elem.html($('').html('No results').attr('style','text-align: center; font-weight: bold; font-size: 1.2em;'));
else {
elemliststr = elem.attr('id') + '-list';
elem.html($('
elemlistobj = $('#' + elemliststr);
$.each(data.results, function(i, item) {
elemlistobj.append($('
});
elem.append($('').html($('').html('More Results').attr('href', 'http://search.twitter.com/search?q=' + query).attr('target', '_blank')).attr('style', 'padding-top: 10px; font-weight: bold; text-align: center;'));
}
}
);
}
We use jQuery's getJSON call to get the JSON results from these services. The "&callback=?" at the end of both the JSON queries tells getJSON that these are JSONP requests - jQuery automagically substitutes the name of the function the results of the query should be fed to.
The "elem" and "searchtype" arguments being sent to the "getGoogleContent" function allow me to call the same function for all News, Web and Video searches like so:
getGoogleContent($('#news-tab'), 'news', query);
getGoogleContent($('#youtube-tab'), 'video', query);
getGoogleContent($('#web-tab'), 'web', query);
Another thing to note here is the usefulness of FireBug. When I was starting out making these queries, I relied on console.log to see the returned object structure (since neither Google nor Twitter specify it) which then allowed me to make the right calls for the relevant data.
So there you go - a quick, easy and scalable way of using Google and Twitter's API's to bring in information into your website.
No comments:
Post a Comment