HTML and CSS Reference
In-Depth Information
EXAMPLE
18.2 (
CONTINUED
)
<script type="text/javascript">
3
function goAjax()
{
4
var ajaxRequest=createRequest()
; *
Cross-browser check;
Get a new XMLHttpRequest object
*/
if( ajaxRequest != false){ /*
If we got back a request
object create callback function to check state of the
request
*/
5
ajaxRequest.onreadystatechange = function(){
6
if(ajaxRequest.readyState == 4){
7
if(ajaxRequest.status==200){
8
document.getElementById("message").innerHTML=
ajaxRequest.responseText;
}
}
} // End callback function
9
yourname=document.getElementById("username").value
;
10
ajaxRequest.open("GET",
"http://localhost/serverTime.php?name=" + yourname +
"&random=" + Math.random()
);
11
ajaxRequest.send(null);
} //End if
else{ alert("Browser problem was encountered!");}
} // End ajaxFunction()
</script>
</head>
<body>
<form name="myForm">
12
Your name: <input type="text"
onKeyUp="goAjax()
;"
name="username" id="username" /> <br />
<p>
13
<div id="message" class="divStyle">
<!-- This is where the Ajax output will be displayed -->
</div>
</p>
</form>
</body>
</html
EXPLANATION
1
The CSS style sheet is loaded from a file called “ajaxintro.css”. It defines the back-
ground color as aliceblue and the style of the <div> contents that will be displayed
in the browser, a dark green container with white letters. See Example 18.3.
2
A .js file is loaded here. It contains a JavaScript function that performs a cross-
browser check and creates and returns the
XMLHttpRequest
object. If the object
cannot be created, the function will return
false
. Example 18.4 contains the func-
tion found in an external file called “ajaxCreateRequest.js”.