HTML and CSS Reference
In-Depth Information
Making Requests Using XMLHttpRequest
A very common and popular way of communicating with the server is the XMLHttpRequest object. The
XMLHttpRequest object allows you to programmatically make HTTP requests to the web server, such as GET ,
POST , PUT , and DELETE . The primary reason for the popularity of XMLHttpRequest is that the leading browsers
support it. XMLHttpRequest was first introduced by Internet Explorer, but it was soon absorbed in all the
other browsers too. Today, XMLHttpRequest is the basis of most Ajax-based communication. In fact, the
jQuery $.ajax() method that you've been using throughout this topic internally uses XMLHttpRequest for
its functionality. Using XMLHttpRequest , you can make synchronous and asynchronous requests to the web
server, although asynchronous mode is used more often.
XMLHttpRequest existed prior to HTML5, but with HTML5 it has been improved. Some of the main
improvements include the following:
• You can make cross-origin requests using the XMLHttpRequest object and the CORS
specifications.
• You can track the progress of data download and upload operations using progress
events.
XMLHttpRequest now supports sending binary data.
Together, these improvements to the XMLHttpRequest object are referred as Level 2 . You used
XMLHttpRequest briefly while working with web workers. The following sections dissect the XMLHttpRequest
object in more details.
Properties of XMLHttpRequest
Before using the XMLHttpRequest object, let's take a quick look at its properties, methods, and events. Table
11-1 lists the properties of XMLHttpRequest . Some of these properties are set before making a request, and
others are accessed after the completion of the request.
Table 11-1. Properties of the XMLHttpRequest Object
Property
Description
readyState
Indicates the state of a request at a given point of time. The readyState property can
change during the lifetime of a request and can take one of the following values:
0—The request has not yet been sent to the server.
1—The request has been opened by the server using the open() method, but the send()
method hasn't yet been called.
2—The send() method has been called, and the response headers and status are
available.
3—The response is being downloaded but isn't complete.
4—The operation is complete.
The readyState property is commonly used inside the readystatechange event.
responseType
Tells the server the desired response type. Common values include text , json , and
document .
responseText
Returns the response to the request as text data.
responseXML
Returns the response to the request as an XML document.
status
Indicates an HTTP status code (such as 200).
statusText
Indicates an HTTP status text (such as “200 OK”).
 
Search WWH ::




Custom Search