Java Reference
In-Depth Information
while the
XMLHttpRequest
object awaits a response from the server. Asynchronous mode is the
default behavior of
XMLHttpRequest
, so you can usually omit the third argument to
open()
.
Note
In the past, it was considered best practice to pass
true
as the third
argument.
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 request = new XMLHttpRequest();
request.open("GET", "
http://localhost/myTextFile.txt", f
false);
request.send(null);
This code makes a
GET
request to retrieve a file called
myTextFile.txt
in synchronous mode.
Calling the
send()
method sends the request to the server.
WarNiNg
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 find the requested file. With this in mind, consider the following example:
var request = new XMLHttpRequest();
request.open("GET", "
http://localhost/myTextFile.txt", f
false);
request.send(null);
var status = request.status;
if (status == 200) {
alert("The text file was found!");
} else if (status == 404) {
alert("The text file could not be found!");
} else {
alert("The server returned a status code of " + 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 file exists. If the file doesn't exist (status
404
), the user sees a message stating that the server cannot find the file. Finally, an
alert
box tells
the user the status code if it equals something other than
200
or
404
.
Many different HTTP status codes exist, 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 request = new XMLHttpRequest();
request.open("GET", "
http://localhost/myTextFile.txt", f
false);