Java Reference
In-Depth Information
Chapter 12; as a refresher, requests made in synchronous mode halt all JavaScript code from executing
until a response is received from the server.
Asynchronous mode is preferred for real applications.
The next step is to send the request; do this with the send() method. This method accepts one argument,
which is a string that contains the request body to send along with the request. GET requests do not contain
any information, so pass null as the argument.
var oHttp = createXmlHttpRequest();
oHttp.open(“GET”, “http://localhost/myTextFile.txt”, false);
oHttp.send(null);
This code makes a GET request to retrieve a fi le called myTextFile.txt in synchronous mode. Calling
the send() method sends the request to the server.
The
send()
method requires an argument to be passed; even if it is
null
.
Each
XMLHttpRequest
object has a
status
property. This property contains the HTTP status code sent
with the server's response. The server returns a status of
200
for a successful request, and one of
404
if
it cannot fi nd the requested fi le. With this in mind, consider the following example:
var oHttp = createXmlHttpRequest();
oHttp.open(“GET”, “http://localhost/myTextFile.txt”, false);
oHttp.send(null);
if (oHttp.status == 200)
{
alert(“The text file was found!”);
}
else if (oHttp.status == 404)
{
alert(“The text file could not be found!”);
}
else
{
alert(“The server returned a status code of ” + oHttp.status);
}
This code checks the status property to determine what message to display to the user. If successful (a
status of
200
), an alert box tells the user the request fi le exists. If the fi le doesn't exist (status
404
), then
the user sees a message stating that the server cannot fi nd the fi le. Finally, an alert box tells the user the
status code if it equals something other than
200
or
404
.
There are many different HTTP status codes, and checking for every code is not feasible. Most of the
time, you should only be concerned with whether your request is successful. Therefore, you can cut the
previous code down to this:
var oHttp = createXmlHttpRequest();
oHttp.open(“GET”, “http://localhost/myTextFile.txt”, false);