<html>
<head>
<title>An example to show how AJAX works</title>
</head>
<body>
<script language="javascript">
var xmlhttp
function fireAJAX(str)
{
// avoiding bothering the server too much
if (str.length==0)
{
document.getElementById("myHook").innerHTML="";
return;
}
// get an XMLHttpRequest object
xmlhttp = getXmlHttpObject();
if(xmlhttp==null)
{
alert ("Your browser does not support XMLHttpRequest!");
return;
}
// register the lister before sending out the request
xmlhttp.onreadystatechange = listenerForStateChange;
// URL to the target server for response
var url = "suggest.jsp?s=" + str;
url = url + "?sid=" + Math.random(); // to avoid cached results
// send out the request
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function listenerForStateChange()
{
if(xmlhttp.readyState==4)
{
document.getElementById("myHook").innerHTML = xmlhttp.responseText;
}else{
// do some funcy thing
}
}
function getXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
<form>
Name: <input type="text" onkeyup="fireAJAX(this.value);" />
Suggestions: <span id="myHook">This part will be soon replaced
by response from server.</span>
</form>
</body>
</html>