Java Reference
In-Depth Information
}
}
this.request.onreadystatechange = reqReadyStateChange;
}
 
HttpRequest.prototype.send = function () {
this.request.send(null);
};
Save this file as httpre q uest.js . You'll use it later in the chapter.
The goal of this module was to make asynchronous requests easier to use, so let's look at a brief
code‐only example and see if that goal was accomplished.
The first thing you need is a function to handle the data received from the request; this function gets
passed to the HttpRequest constructor:
function handleData(text) {
alert(text);
}
This code defines a function called handleData() that accepts one argument called text . When
executed, the function merely alerts the data passed to it. Now create an HttpRequest object and
send the request:
var request = new HttpRequest(
" http://localhost/myTextFile.txt", h andleData);
 
request.send();
Pass the text file's location and a pointer of the handleData() function to the constructor, and
send the request with the send() method. The handleData() function is called in the event of a
successful request.
This module encapsulates the code related to asynchronous XMLHttpRequest requests nicely. You
don't have to worry about creating the request object, handling the readystatechange event, or
checking the request's status ; the HttpRequest module does it all for you.
Validating form fields With ajax
You've probably seen it many times: registering as a new user on a website's forum or signing up
for web‐based e‐mail, only to find that your desired username is taken. Of course, you don't find
this out until after you've filled out the entire form, submitted it, and watched the page reload with
new data (not to mention that you've lost some of the data you entered). As you can attest, form
validation can be a frustrating experience. Thankfully, Ajax can soften this experience by sending
data to the server before submitting the form—allowing the server to validate the data, and letting
the user know the outcome of the validation without reloading the page!
In this section, you create a form that uses Ajax techniques to validate form fields. It's possible to
approach building such a form in a variety of ways; the easiest of which to implement provides a
link that initiates an HTTP request to the server application to check whether the user's desired
information is available to use.
 
Search WWH ::




Custom Search