A comprehensive analysis of JavaScript XMLHttpRequest objects

Source: Internet
Author: User

Reprint: http://www.jb51.net/article/23175.htm

First, Introduction

Asynchronous JavaScript and XML (AJAX) is a special term used to implement the process of data interaction between client script and server. The advantage of this technique is that it provides developers with a way to retrieve data from a Web server without having to return the page that the user is currently observing to the server. In conjunction with the modern browser's programmatic code (JAVASCRIPT) that accesses the DOM structure of the browser to dynamically change the support of the displayed content, Ajax lets developers update the displayed HTML content on the browser side without having to refresh the page. In other words, Ajax can make browser-based applications more interactive and more like traditional desktop applications.

Google's Gmail and Outlook Express are some of the two familiar examples of Ajax-using technologies. Also, Ajax can be used in any client-side scripting language, including Javascript,jscript and VBScript.

Ajax uses an object-xmlhttprequest-built into all modern browsers to send and receive HTTP request and response information. An HTTP request sent via an XMLHttpRequest object does not require that a <form> element be owned or mailed back to the page. The "A" in Ajax represents "async", which means that the send () method of the XMLHttpRequest object can be returned immediately, allowing other html/javascript on the Web page to continue its browser-side processing while the server processes the HTTP request and sends a response. Although the request is asynchronous by default, you can choose to send a synchronization request, which pauses 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 its Internet Explorer (IE) 5. Other browser manufacturers who recognize the importance of this object have implemented XMLHttpRequest objects within their browsers, but as a native JavaScript object instead of as an ActiveX object. Now, after realizing this type of value and security features, Microsoft has implemented XMLHttpRequest as a Window object property in its IE 7. Fortunately, although the details of its implementation (and hence the invocation) are different, all browser implementations have similar functionality and are essentially the same method. Currently, the organization is working to standardize the XMLHttpRequest object, and a draft of the code has been issued.

This article will discuss the XMLHttpRequest Object API in detail and will explain all of its properties and methods.

   Ii. properties and events for XMLHttpRequest objects

The XMLHttpRequest object exposes various properties, methods, and events to facilitate scripting and control of HTTP requests and responses. Below, we will discuss this in more detail.
ReadyState Property

When an XMLHttpRequest object sends an HTTP request to the server, it undergoes several states: Waits until the request is processed, and then receives a response. In this way, the script responds correctly to various states the-xmlhttprequest object exposes a ReadyState property that describes the current state of the object, as shown in table 1.

Table 1. A list of ReadyState property values for the XMLHttpRequest object.

ReadyState value Describe
0 Describes an "uninitialized" state, in which a XMLHttpRequest object has been created, but has not yet been initialized.
1 Describes a "send" state; At this point, the code has called the XMLHttpRequest Open () method and XMLHttpRequest is ready to send a request to the server.
2 Describes a "send" state; At this point, a request has been sent to the server by means of the Send () method, but no response has yet been received.
3 Describes a "receiving" state where HTTP response header information has been received, but the body portion of the message has not been fully received at the end.
4 Describes a "loaded" state, at which time the response has been fully received.


onReadyStateChange Event

The XMLHttpRequest object fires a ReadyStateChange event regardless of when the readystate value has changed. Where the onReadyStateChange property receives a EventListener value-indicates to the method that the object will be activated regardless of when the readystate value has changed. The

ResponseText property

This ResponseText property contains the text content of the HTTP response received by the client. When the readystate value is 0, 1, or 2 o'clock, ResponseText contains an empty string. When the readystate value is 3 (receiving), the response contains the response information that the client has not yet completed. When ReadyState is 4 (loaded), the responsetext contains the complete response information.

Responsexml Property

This Responsexml property is used to describe the XML response when a full HTTP response is received (ReadyState is 4), at which point the Content-type header specifies MIME (media) The type is text/xml,application/xml or ends with +xml. If the Content-type header does not contain one of these media types, then the value of Responsexml is null. The value of the responsexml is also null whenever the readystate value is not 4.

In fact, this Responsexml property value is an object of the document interface type that describes the document being parsed. If the document cannot be parsed (for example, if the document is not well-structured or does not support the corresponding character encoding of the document), then the value of Responsexml will be null. The

Status property

This status property describes the HTTP status code and is of type short. Also, this status property is available only if the ReadyState value is 3 (in the receiving) or 4 (loaded). When the value of readystate is less than 3 o'clock attempting to access the status value throws an exception. The

StatusText property

This statustext property describes the HTTP status code text, and is only available if the ReadyState value is 3 or 4. Attempting to access the StatusText property when ReadyState is a different value throws an exception.

Third, the method of XMLHttpRequest object

The XMLHttpRequest object provides various methods for initializing and processing HTTP requests, which are discussed in detail in the following sections.

Abort () method

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

Open () method

You need to call open (domstring method,domstring uri,boolean async,domstring username,domstring password) Method initializes a XMLHttpRequest object. Where the method parameter is required-to specify the HTTP method (Get,post,put,delete or head) that you want to use to send the request. The Post method should be used in order to send data to the server, and the Get method should be used in order to retrieve data from the server side. In addition, the URI parameter is used to specify the URI of the server to which the XMLHttpRequest object sends the request. With the help of the Window.document.baseURI property, the URI is parsed to an absolute uri-in other words, you can use the relative uri-that it will be parsed in the same way that the browser resolves the relative URI. The Async parameter specifies whether the request is asynchronous-The default value is true. In order to send a synchronous request, this parameter needs to be set to false. For servers that require authentication, you can provide optional user name and password parameters. After calling the open () method, the XMLHttpRequest object sets its ReadyState property to 1 (open) and resets the ResponseText, Responsexml, status, and StatusText properties to their initial values. In addition, it resets the request header. Note that if you call the open () method and the readystate is 4 at this point, the XMLHttpRequest object resets the values.

Send () method

After you have prepared a request by calling the open () method, you need to send the request to the server. You can call the Send () method only if the readystate value is 1 o'clock, otherwise the XMLHttpRequest object throws an exception. The request is sent to the server using the parameters provided to the open () method. When the async parameter is true, the Send () method returns immediately, allowing other client script processing to continue. After calling the Send () method, the XMLHttpRequest object sets the value of ReadyState to 2 (send). When the server responds, the XMLHttpRequest object will set ReadyState to 3 (receiving) If there is any message body before receiving the body of the message. When the request finishes loading, it sets the readystate to 4 (loaded). For a head type request, it will set the ReadyState value to 3 before setting it to 4 immediately.

The Send () method uses an optional parameter-the parameter can contain data of a mutable type. Typically, you use it and send data to the server via the Post method. In addition, you can explicitly call the Send () method with a null parameter, just as you would call it without a parameter. For most other data types, before calling the Send () method, you should use the setRequestHeader () method (see explanation later) to set the Content-type header first. If the type of the data parameter in the Send (data) method is domstring, then the data will be encoded as UTF-8. If the data is of document type, 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 requested header information. When the readystate value is 1 o'clock, 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 header value of the response. This method can be called only if the readystate value is 3 or 4 (in other words, after the response header is available), otherwise the method returns an empty string.

getAllResponseHeaders () method

The getAllResponseHeaders () method returns all the response headers in a string (each header takes on a separate line). If the value of readystate is not 3 or 4, the method returns NULL.

Iv. Sending requests

In Ajax, many requests to use XMLHttpRequest are initialized from an HTML event, such as a button click (onclick) or a key (onkeypress) that invokes a JavaScript function. Ajax supports a variety of applications, including form validation. Sometimes, a unique form field is required to be checked before other contents of the form are populated. For example, a single userid is required to register a form. If you do not use AJAX technology to validate this userid domain, then the entire form must be populated and committed. If the userid is not valid, this form must be resubmitted. For example, a form field corresponding to a catalog ID that requires validation on the server side may be specified in the following form:







Catalog Id:


The preceding HTML uses the Validationmessage div to display a checksum message corresponding to the catalog ID of this input domain. The onkeyup event invokes a JavaScript sendrequest () function. This sendrequest () function creates a XMLHttpRequest object. The process of creating a XMLHttpRequest object differs depending on the browser implementation. If the browser supports the XMLHttpRequest object as a window property (all normal browsers are like this, except IE 5 and IE 6), then the code can call the XMLHttpRequest constructor. If the browser implements the XMLHttpRequest object as a ActiveXObject object (as in IE 5 and IE 6), then the code can use the ActiveXObject constructor. The following function calls an init () function, which examines and determines the appropriate creation method to use-before creating and returning an object.


Next, you need to initialize the XMLHttpRequest object with the open () method-Specify the HTTP method and the server URL to use.

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, a call to URL Validateform activates a servlet on the server side, but you should be able to notice that the server-side technology is not fundamental; in fact, the URL might be a asp,asp. NET or PHP page or a Web service-this does not matter, as long as the page can return a response-indicating whether the Catalogid value is valid-can. Because you are making an asynchronous call, you need to register a XMLHttpRequest object that will invoke the callback event handler-called when its readystate value changes. Remember that changes to the readystate value will trigger a ReadyStateChange event. You can use the onReadyStateChange property to register the callback event handler.

Xmlhttpreq.onreadystatechange=processrequest;


Then we need to send the request using the Send () method. 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);

V. Processing of requests

In this example, because the HTTP method is get, the receive servlet on the server side invokes a doget () method that retrieves the value of the Catalogid parameter specified in the URL and checks its validity from a database.

The servlet in this example needs to construct a response sent to the client, and this example returns an XML type, so it sets the HTTP content type of the response to Text/xml and sets the Cache-control header to No-cache. Setting the Cache-control header prevents the browser from simply reloading the page from the cache.

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 side is an XML DOM object that creates an XML string that contains the instructions to be processed on the client. In addition, the XML string must have a root element.

OUT.PRINTLN (" valid ");


Note the XMLHttpRequest object is designed to handle responses that consist of plain text or XML, but one response can also be a different type if the user agent (UA) supports this type of content.

When the request state changes, the XMLHttpRequest object invokes the event handler registered with onReadyStateChange. Therefore, before processing the response, your event handler should first check the value of the readystate and the HTTP status. When the request finishes loading (the readystate value is 4) and the response is completed (the HTTP status is "OK"), you can call a JavaScript function to process the response. The following script is responsible for checking the corresponding values and calling a ProcessResponse () method when the response is complete.

function ProcessRequest () {
if (xmlhttpreq.readystate==4) {
if (xmlhttpreq.status==200) {
ProcessResponse ();
}
}
}


The ProcessResponse () method uses the Responsexml and ResponseText properties of the XMLHttpRequest object to retrieve the HTTP response. As explained above, this responsexml is only available if the media type of the response is Text/xml,application/xml or ends with +xml. This ResponseText property returns the response as plain text. For an XML response, you will retrieve the content as follows:

var msg=xmlhttpreq.responsexml;


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

var catalogid=msg.getelementsbytagname ("Catalogid") [0].firstchild.nodevalue;


Finally, by updating the HTML content in the Validationmessage div of the Web page and with the help of the innerHTML property, you can test the element value to create a message to display:

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

Above is the implementation of all the details used by the XMLHttpRequest object. By not having to send a Web page to the server for data transfer, the XMLHttpRequest object provides a dynamic interaction capability between the client and the server. You can use JavaScript to start a request and process the corresponding return value, and then use the browser's Dom method to update the data in the page.

A comprehensive analysis of JavaScript XMLHttpRequest objects

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.