Comprehensive Analysis of javascript XMLHttpRequest objects

Source: Internet
Author: User

I. Introduction

Asynchronous JavaScript and XML (AJAX) are special terms used to implement data interaction between client scripts and servers. The advantage of this technology is that it provides developers with a way to retrieve data from the Web server without returning the pages that users are currently observing to the server. It works with modern browsers to dynamically change the support of the displayed content by accessing the programming code (JavaScript) of the browser's DOM structure, AJAX allows developers to update the displayed HTML content on the browser without refreshing the page. In other words, AJAX can make browser-based applications more interactive and more similar to traditional desktop applications.

Google's Gmail and Outlook Express are two familiar examples of AJAX technology. Besides, AJAX can be used in any client scripting language, including JavaScript, Jscript, and VBScript.

AJAX uses XMLHttpRequest, an object built into all modern browsers, to send and receive HTTP requests and responses. An HTTP request sent through an XMLHttpRequest object does not require the page to have or send back a <form> element. "A" in AJAX represents "Asynchronous", which means that the send () method of the XMLHttpRequest object can be returned immediately, in this way, other HTML/JavaScript on the web page can be processed by the browser, and the server processes HTTP requests and sends responses. Although the request is asynchronous by default, you can choose to send a synchronous request, which will suspend the processing of other web pages until the page receives a response from the server.

Microsoft introduced the XMLHttpRequest object as an ActiveX Object in Internet Explorer (IE) 5. Other browser manufacturers that recognize the importance of this object have also implemented XMLHttpRequest objects in their browsers, but as a local JavaScript Object rather than an ActiveX object. Now, after realizing the value and security features of this type, Microsoft has implemented XMLHttpRequest as a window object attribute in its IE 7. Fortunately, although its implementation (and thus the call method) is different, all browser implementations have similar functions and are essentially the same method. Currently, W3C organizations are working to standardize XMLHttpRequest objects and have released a draft on this W3C specification.

This article will discuss in detail the XMLHttpRequest object API and explain all its attributes and methods.

  Ii. attributes and events of the XMLHttpRequest object

The XMLHttpRequest object exposes various attributes, methods, and events to facilitate scripting and control HTTP requests and responses. Next, we will discuss this in detail.
ReadyState attributes

When an XMLHttpRequest object sends an HTTP request to the server, it goes through several states: waiting until the request is processed; then, it receives a response. In this way, the script correctly responds to various statuses-the XMLHttpRequest object exposes the readyState attribute describing the current state of the object, as shown in table 1.

Table 1. List of ReadyState attribute values of the XMLHttpRequest object.

ReadyState Value Description
0 Describes the state of "not initialized". At this time, an XMLHttpRequest object has been created but has not been initialized.
1 Describes a "send" status. At this time, the Code has called the XMLHttpRequest open () method and XMLHttpRequest is ready to send a request to the server.
2 Describes a "send" status. At this time, a request has been sent to the server through the send () method, but no response has been received.
3 Description: A "receiving" status. At this time, the HTTP response header information has been received, but the message body has not completely received.
4 Describes a "loaded" status. At this time, the response has been fully received.


Onreadystatechange event

No matter when the value of readyState changes, the XMLHttpRequest object will trigger a readystatechange event. The onreadystatechange property receives an EventListener value-instructs the method that the object will be activated no matter when the value of readyState changes.

ResponseText attributes

This responseText property contains the text content of the HTTP response received by the client. When the value of readyState is 0, 1, or 2, responseText contains an empty string. When the value of readyState is 3 (receiving), the response contains the uncompleted response information from the client. When readyState is 4 (loaded), The responseText contains the complete response information.

ResponseXML attributes

This responseXML attribute is used to describe the XML response when a complete HTTP response is received (readyState is 4). In this case, the Content-Type Header specifies that the MIME (media) Type is text/xml, application/xml may end with + xml. If the Content-Type Header does not contain any of these media types, the responseXML value is null. Whenever the value of readyState is not 4, the value of responseXML is also null.

In fact, this responseXML property value is a document interface type object used to describe the document to be analyzed. If the document cannot be analyzed (for example, if the document is not a good structure or does not support the corresponding character encoding of the document), the value of responseXML is null.

Status attribute

This status attribute describes the HTTP status code and its type is short. This status attribute is available only when the readyState value is 3 (receiving) or 4 (loaded. When the value of readyState is less than 3, an exception is thrown when you try to access the value of status.

StatusText attributes

This statusText attribute describes the HTTP status code text, and is available only when the readyState value is 3 or 4. When readyState is another value, an exception occurs when you attempt to access the statusText attribute.

3. XMLHttpRequest object Method

The XMLHttpRequest object provides various methods for initializing and processing HTTP requests.

Abort () method

You can use this abort () method to pause the HTTP request associated with an XMLHttpRequest object and reset the object to the uninitialized state.

Open () method

You need to call the open (DOMString method, DOMString uri, boolean async, DOMString username, DOMString password) method to initialize an XMLHttpRequest object. The method parameter must be provided to specify the HTTP method (GET, POST, PUT, DELETE, or HEAD) You want to send the request ). To send data to the server, the POST method should be used; to retrieve data from the server, the GET method should be used. In addition, the uri parameter is used to specify the URI of the server to which the XMLHttpRequest object sends the request. The uri is parsed as an absolute URI-in other words, you can use a relative URI-it will be parsed in the same way as the URI relative to browser resolution. The async parameter specifies whether the request is asynchronous-the default value is true. To send a synchronization request, set this parameter to false. For servers that require authentication, You can provide optional user name and password parameters. After the open () method is called, the XMLHttpRequest object sets its readyState attribute to 1 (open) and resets the responseText, responseXML, status, and statusText attributes to their initial values. In addition, it also resets the request header. Note: If you call the open () method and the readyState is 4 at this time, the XMLHttpRequest object will reset these values.

Send () method

After a request is prepared by calling the open () method, you need to send the request to the server. You can call the send () method only when the value of readyState is 1. Otherwise, the XMLHttpRequest object will cause an exception. The request is sent to the server using parameters provided to the open () method. When the async parameter is true, the send () method returns immediately, allowing other client scripts to continue processing. After the send () method is called, the XMLHttpRequest object sets the value of readyState to 2 (send ). When the server responds, if any message body exists before receiving the message body, the XMLHttpRequest object sets readyState to 3 (receiving ). When the request completes loading, it sets readyState to 4 (loaded ). For a HEAD-type request, it will set it to 4 immediately after setting the readyState value to 3.

The send () method uses an optional parameter-this parameter can contain variable types of data. Typically, you use it and send data to the server through the POST method. In addition, you can explicitly call the send () method using the null parameter, which is the same as calling it without a parameter. For most other data types, use the setRequestHeader () method (see the description below) to set the Content-Type Header before calling the send () method. If the type of the data parameter in the send (data) method is DOMString, the data is encoded as the UTF-8. If the data type is Document, the data will be serialized using the encoding specified by data. xmlEncoding.

SetRequestHeader () method

The setRequestHeader (DOMString header, DOMString value) method is used to set the request header information. When the value of readyState is 1, you can call this method after calling the open () method; otherwise, you will get an exception.

GetResponseHeader () method

The getResponseHeader (DOMString header, value) method is used to retrieve the response header value. This method can be called only when the value of readyState is 3 or 4 (in other words, after the response header is available); otherwise, an empty string is returned.

GetAllResponseHeaders () method

The getAllResponseHeaders () method returns all Response Headers in the form of a string (each header occupies a single line ). If the value of readyState is not 3 or 4, this method returns null.

4. Send a request

In AJAX, many requests that use XMLHttpRequest are initiated from an HTML event (for example, an onclick button that calls a JavaScript function or an onkeypress. AJAX supports various applications, including form verification. Sometimes, a unique form field needs to be verified before filling in other content of the form. For example, you must use a unique UserID for the registration form. If AJAX technology is not used to verify this UserID field, the entire form must be filled and submitted. If this UserID is not valid, the form must be resubmitted. For example, a form field corresponding to a Catalog ID that requires verification on the server may be specified in the following form:

<Form name = "validationForm" action = "validateForm" method = "post">
<Table>
<Tr> <td> Catalog Id: </td>
<Td>
<Input type = "text" size = "20" id = "catalogId" name = "catalogId" autocomplete = "off" onkeyup = "sendRequest ()">
</Td>
<Td> <div id = "validationMessage"> </div> </td>
</Tr>
</Table> </form>

The preceding HTML uses validationMessage div to display a verification message corresponding to the input domain Catalog Id. The onkeyup event calls a JavaScript sendRequest () function. This sendRequest () function creates an XMLHttpRequest object. The process of creating an XMLHttpRequest object varies with browser implementations. If the browser supports the XMLHttpRequest object as a window attribute (this applies to all common browsers except IE 5 and IE 6), the code can call the XMLHttpRequest constructor. If the browser implements the XMLHttpRequest object as an ActiveXObject object (like in IE 5 and IE 6), the code can use the ActiveXObject constructor. The following function calls an init () function, which is responsible for checking and deciding the appropriate creation method to use-before creating and returning objects.

<Script type = "text/javascript">
Function sendRequest (){
Var xmlHttpReq = init ();
Function init (){
If (window. XMLHttpRequest ){
Return new XMLHttpRequest ();
}
Else if (window. ActiveXObject ){
Return new ActiveXObject ("Microsoft. XMLHTTP ");
}
}
</Script>

Next, you need to use the Open () method to initialize the XMLHttpRequest object-specify the HTTP method and the server URL to be used.

Var catalogId = encodeURIComponent (document. getElementById ("catalogId"). value );
XmlHttpReq. open ("GET", "validateForm? CatalogId = "+ catalogId, true );

By default, HTTP requests sent using XMLHttpRequest are asynchronous, but you can explicitly set the async parameter to true, as shown above.
In this case, the URL validateForm call will activate a servlet on the server, but you should be able to note that the server-side technology is not fundamental; in fact, the URL may be an ASP, ASP. NET or PHP page or a Web Service-this does not matter as long as the page returns a response-indicating whether the CatalogID value is valid. Because you are making an asynchronous call, you need to register an XMLHttpRequest object to call the callback event processor-called when its readyState value changes. Remember, changing the value of readyState will trigger a readystatechange event. You can use the onreadystatechange attribute to register the callback event processor.

XmlHttpReq. onreadystatechange = processRequest;

Then, we need to use the send () method to send the request. Because this request uses the http get method, you can call the send () method without specifying a parameter or using a null parameter.

XmlHttpReq. send (null );

5. Process requests

In this example, because the HTTP method is GET, the receiving servlet on the server will call a doGet () method, which will retrieve the value of the catalogId parameter specified in the URL, and check its validity from a database.

In this example, the servlet needs to construct a response sent to the client. In addition, the XML type is returned in this example. Therefore, it sets the HTTP content type of the response to text/xml and the Cache-Control header to no-cache. Setting the Cache-Control header prevents the browser from simply reloading pages from caching.

Public void doGet (HttpServletRequest request,
HttpServletResponse response)
Throws ServletException, IOException {
...
...
Response. setContentType ("text/xml ");
Response. setHeader ("Cache-Control", "no-cache ");
}

The response from the server is an xml dom object that creates an XML string containing instructions to be processed on the client. In addition, the XML string must have a root element.

Out. println ("<catalogId> valid </catalogId> ");

[Note] the XMLHttpRequest object is designed to process responses composed of common text or XML. However, a response may also be of another type if the user agent (UA) this content type is supported.

When the Request status changes, the XMLHttpRequest object calls the event processor registered with onreadystatechange. Therefore, before processing the response, your event processor should first check the value of readyState and HTTP status. When the request is loaded (the value of readyState is 4) and the response is completed (the HTTP status is "OK"), you can call a JavaScript function to process the response content. The following script checks the corresponding values when the response is complete and calls a processResponse () method.

Function processRequest (){
If (xmlHttpReq. readyState = 4 ){
If (xmlHttpReq. status = 200 ){
ProcessResponse ();
}
}
}

The processResponse () method uses the responseXML and responseText attributes of the XMLHttpRequest object to retrieve HTTP responses. As explained above, this responseXML is only available when the response media type is text/xml, application/xml, or ends with + xml. This responseText property will return a response in the form of plain text. For an XML response, you will retrieve the content as follows:

Var msg = xmlHttpReq. responseXML;

With the help of XML stored in the msg variable, you can use the DOM method getElementsByTagName () to retrieve the value of this element:

Var catalogId = msg. getElementsByTagName ("catalogId") [0]. firstChild. nodeValue;

Finally, by updating the HTML content in the validationMessage div on the web page and using the innerHTML attribute, you can test the element value to create a message to be displayed:

If (catalogId = "valid "){
Var validationMessage = document. getElementById ("validationMessage ");
ValidationMessage. innerHTML = "Catalog Id is Valid ";
}
Else
{
Var validationMessage = document. getElementById ("validationMessage ");
ValidationMessage. innerHTML = "Catalog Id is not Valid ";
}

   Vi. Summary

The above is the implementation of all the details used by the XMLHttpRequest object. The XMLHttpRequest object provides a dynamic interaction between the client and the server by transmitting data without having to send Web pages to the server. You can use JavaScript to start a request and process the returned values, and then use the DOM method of the browser to update the data on the page.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.