Java Reference
In-Depth Information
the server responds. After the client receives the server's message, the connection is closed.
The communication is asynchronous from the perspective of the user because the AJAX
call is performed on a separate thread so that the UI doesn't freeze.
AJAX is used in many common scenarios to avoid a full-page reload. Consider the example
of the shipping page for ActionBazaar. The winning bidder must specify their address and
select a shipping method, such as FedEx, UPS, or USPS. The shipping cost will depend on
the ZIP code. To avoid a transition to another web page, thereby incurring a full-page load,
an AJAX call to the server can retrieve the estimated shipping costs once a valid ZIP code
has been entered. This reduces the load on the server, sends fewer pages to the server, and
improves the overall usability of the shipping process.
Although the definition of AJAX includes XML, JSON can be used instead of XML. The
data that's received from an AJAX call can be JSON, XML, or even HTML. All commu-
nication is done via HTTP or HTTPS. From the perspective of the server, an AJAX invoc-
ation looks like any other HTTP request.
At the heart of AJAX is the XMLHttpRequest object. This is a built-in JavaScript object
with several methods for opening connections, sending data, and so on. An example of us-
ing this method is shown in the next listing.
Listing 14.6. AJAX method invocation from JavaScript
The code in this listing demonstrates the basic parts of an AJAX call. You first instantiate
the XMLHttpRequest object
and then set the callback function
. When the call-
back function is invoked, you check to see whether it was successful
. To initiate the
call, you first open a connection
and then send the request
.
Search WWH ::




Custom Search