Information Technology Reference
In-Depth Information
Listing 3-6. Javascript for I Love Ham -Part 2
functioninit() {
window.scrollTo(0, 1);
//reset the correct answer and currentRound array
correct = '';
choice = getRandom();
$('ul, section').removeClass();
$('ul').empty();
//find out which item has more search results
for(i=0;i<choice.length;i++){
var position = i;
$.getJSON(' http://search.twitter.com/search.json?rpp=100&q=' +
choice[i].replace(/\s/g,'%20') + '&callback=?', function(data) {
//check the length of results for each search
//then set them to the "correct" variable
correct.push(data.results.length);
});
}
// generate the buttons for this round
buildQuiz();
}
Here we have our init() function, which will be called and run later in the application
after the DOM (Document Object Model) has loaded. When using the Twitter API, there
are several parameters youcould send with yoursearches. Let's run through them
quickly!
Rpp tells the API how many results we want back per page. In this
case, we are pulling in the maximum of 100 results per search.
Q is the parameter that will house our search query.
Callback is triggered to make sure the API sends back data in a
JSONP format so we are not presented with any cross domain
security issues!
Another thing you will notice above is i in the search query, where we are calling in the
term to search at that time. In that part, I am using the replace() method to search our
string for all spaces and replace them with %20 , which is the URL encoded version of a
space. This allows the search to be sent via a normal HTTP request without messing up
where the page really gets pointed to on the web. To get a better understanding of why
this is necessary, imagine this—someone sends you a link to
http://someawesomesite.com/some aw esome page. Since the URL is broken up, if the
person you sent that link to clicks it, then they would most likely be navigated to a page
with the URL of http://someawesomesite.com/some, and the rest of the URL would be
ignored, but clicking a URL that looked like http://someawesomesite.com/
some%20awesome%20page would take the user exactly where they intended to go. Always
make sure there are no breaks in the URLs that you create (see Figure 3-2)!
Search WWH ::




Custom Search