Thursday, November 09, 2006

 

Calling Google Suggest

Here's a small example on how to leverage the Google Suggest API (http://web.cecs.pdx.edu/~eberhart/web2.0/gs.html):



The code contains the following major blocks:

1) an input field which has a onkeyup event handler:

<input type="text" id="input" onkeyup="javascript:go(document.getElementById('input').value )">


Upon every keystroke, the JS function go is called with the current contents of the input field as a parameter.

2) function go where the actual request is being made. We append the input parameter to the Google Suggest URL as in this example: http://www.google.com/complete/search?hl=en&js=true&qu=ajax. The result is a script calling the function sendRPCDone. This script is loaded into the page as follows:
function go( par )
{
var head = document.getElementsByTagName("head").item(0);
var oScript = document.createElement("script");
oScript.setAttribute("src", "http://www.google.com/complete/search?hl=en&js=true&amp;amp;qu=" + encodeURIComponent( par ));
head.appendChild(oScript);
}

Using DOM, we create a new tag which is placed in head.
This causes the browser to load and execute the script.

3) sendRPCDone

function sendRPCDone(fr,is,cs,ds,pr)
{
output.innerHTML = cs;
}
...
<div id="output">

The script loaded in step 2 calls this function which simply puts the result array in the DOM tree of our page.

This is an example of script based Ajax (i.e. data is transmitted as a JS program rather than regular ASCII text or XML).

Although it is a bit strange, this method has the advantage of working across domains. Using HttpXMLRequest, it would not have been possible to load data from google.com given that the script came from a domain other than google.com

Comments:
This is a very interesting way to handle a cross site situation... Will be giving this some more thought...
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?