CHAPTER 18 ■ AJAX AND JSON^283
//Define the function that will receive
//notifications about state changes.
xhr.onreadystatechange = readyStateChange;
//Set the request header so that PHP
//knows that this is a form submission
xhr.setRequestHeader
("Content-type", "application/x-www-form-urlencoded");
//Post the data to the server
xhr.send(data);
}
function readyStateChange() {
//State 4 means the data is ready
if(xhr.readyState == 4) {
//Check if the server sent any data and the request was 200 ok
if(xhr.responseText && xhr.status == 200) {
json = xhr.responseText;
//Parse the server response, creating a JS array.
try {
suggestionArr = json.parseJSON();
} catch (e) {
//Problem with/parsing JSON data.
}
//Create some HTML
tmpHtml="";
for(i=0, len = suggestionArr.length; i < len; i++) {
tmpHtml += suggestionArr[i] + "<br />";
}
div = document.getElementById("suggestions");
div.innerHTML = tmpHtml;
} //else blank response, 404 request etc.
}
}
</script>
</head>
<body>
<input id="search" type="text" onkeyup="suggest()" />
<div id="suggestions"></div>
</body>
<html>
McArthur_819-9.book Page 283 Friday, February 29, 2008 8:03 AM