AJAX - The Complete Reference

(avery) #1

380 Part II: Developing an Ajax Library^


These are really just global variables that we use as constants to aid readability since
JavaScript lacks true constants.

var ENTER = 13;
var KEYUP = 38;
var KEYDOWN = 40;

Going to network in this example is quite simple. A server-side program is called that
returns matches of letters to a list of the world countries.

function getSuggestions(country)
{
var url = "http://ajaxref.com/ch8/getcountry.php";
var payload = "name=" + country.value;
sendRequest(url, payload);
}

Here the server-side program simply returns a text list of countries that match the letters
that the user is typing:

Now the Ajax communication proceeds, as we have seen in other examples, to invoke a
callback function handleResponse(). In this example, the XHR’s responseText
property is read. It will contain a newline separated list of country suggestions if any. They
are read one at a time and a <div> is created for each to put in the suggestion list menu.
Note that a handler is added to change the state of each selection if the user mouses over or
away from it. Also, a click event handler is set here in case the user clicks a suggestion to set
the field to whatever was clicked. We already saw the capture of a suggestion via keystroke
in the checkKey() function.

function handleResponse(response)
{
var suggestList = document.getElementById("suggestList")
suggestList.innerHTML = "";
Free download pdf