Detailed analysis of XMLHttpRequest objects

Source: Internet
Author: User
Tags object end header http request string valid window access
The XMLHttpRequest object is the technical foundation of all today's Ajax and Web 2.0 applications. Although software distributors and open source communities are now providing a variety of AJAX frameworks to further simplify the use of XMLHttpRequest objects, we still need to understand the detailed work mechanism of this object.

   first, the introduction

Asynchronous JavaScript and XML (AJAX) are a special term used to implement 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 giving back to the server the page that the user is currently looking at. With modern browsers ' programming code (JAVASCRIPT), which accesses the DOM structure of browsers, dynamically changing 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 makes browser-based applications more interactive and similar to traditional desktop applications.

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

Ajax uses an object-xmlhttprequest-built into all modern browsers to deliver and receive HTTP request and response information. An HTTP request sent via the XMLHttpRequest object does not require a element to be owned or sent back in the page. "A" in Ajax represents "asynchronous," which means that the send () method of the XMLHttpRequest object can be returned immediately, allowing other html/javascript on the Web page to continue their browser-side processing while the server processes HTTP requests and sends a response. Although the request is made asynchronously by default, you can choose to send a sync 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 that recognize the importance of this object are also implementing XMLHttpRequest objects in their browsers, but as a local JavaScript object rather than as an ActiveX object. Now, having realized the value and security features of this type, Microsoft has implemented XMLHttpRequest as a Window object attribute in its IE 7. Fortunately, although the details of its implementation (and thus the way it affects the invocation) are different, all browser implementations have similar functionality and are essentially the same method. Currently, the organization is working on the standardization of XMLHttpRequest objects and has issued a draft on the norms of the consortium.

This article discusses the XMLHttpRequest object API in detail and interprets all of its properties and methods.

   Ii. Properties and events of XMLHttpRequest objects

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

When a XMLHttpRequest object sends an HTTP request to the server, it goes through several states: Wait until the request is processed, before it receives a response. In this way, the script responds correctly to various state-xmlhttprequest objects exposing a readystate attribute 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, at which point a XMLHttpRequest object has been created, but has not yet been initialized.
1 Describes a "send" state, at which point the code has invoked the XMLHttpRequest open () method and XMLHttpRequest is ready to send a request to the server.
2 Describes a "send" state, at which point a request has been sent to the server side through the Send () method, but no response has been received.
3 Describes a "receiving" state in which HTTP response header information has been received, but the message body part has not yet fully received the end.
4 Describes a "loaded" state at which time the response has been fully received.

onReadyStateChange Events

The XMLHttpRequest object fires a ReadyStateChange event regardless of when the readystate value changes. 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.

ResponseText Property

This ResponseText property contains the textual 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 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 an XML response when a full HTTP response is received (readystate 4), at which point the Content-type header specifies a MIME (media) type of text/xml,application/xml or A + The end of XML. If the Content-type header does not contain one of these media types, then the Responsexml value is null. Whenever the readystate value is not 4, the value of the responsexml is also null.

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

Status Property

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

StatusText Property

This statustext property describes the HTTP status code text and is only available if the ReadyState value is 3 or 4. An exception is thrown when an attempt is made to access the StatusText property when ReadyState is another value.

   three, the XMLHttpRequest object method

The XMLHttpRequest object provides a variety of methods for initializing and processing HTTP requests, and the following will be discussed individually.

Abort () method

You can use this abort () method to pause an HTTP request associated with a XMLHttpRequest object, thereby resetting the object to an uninitialized state.

Open () method

You need to call open (domstring method,domstring uri,boolean async,domstring username,domstring password) method to initialize a XMLHttpRequest object. Where the method parameter must be provided-used to specify the HTTP methods (Get,post,put,delete or head) you want to use to send the request. In order to send data to the server, the Post method should be used, 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 attribute, the URI is resolved to an absolute uri-in other words, you can use the relative uri-it will be parsed in the same way as the URI that the browser resolves. The Async parameter specifies whether the request is asynchronous-The default value is true. To send a sync request, you need to set this parameter to False. For servers that require authentication, you can provide an optional username and password parameter. After the open () method is called, 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 also resets the request head. Note that if you call the open () method and the readystate is 4 at this time, 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 an argument supplied to the open () method. When the async parameter is true, the Send () method returns immediately, allowing other client script processing to continue. After the Send () method is called, the XMLHttpRequest object sets the value of ReadyState to 2 (sent). When the server responds, the XMLHttpRequest object will set the ReadyState to 3 (in reception) before the message body is received, if any of the message bodies exist. When the request completes 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 mutable types of data. Typically, you use it and post methods to send data to the server. In addition, you can explicitly invoke the Send () method with the null argument, just as you would call it without arguments. For most other data types, before calling the Send () method, you should use the setRequestHeader () method (see later explanation) to set the Content-type head first. If the type of the data parameter in the Send (data) method is domstring, then it will be encoded as UTF-8. If the data is a document type, the data is 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 retrieves the header value of the response. This method can only be invoked if the ReadyState value is 3 or 4 (in other words, after the response head is available);

getAllResponseHeaders () method

The getAllResponseHeaders () method returns all the response headers as a string (each header occupies a single row). If the value of readystate is not 3 or 4, the method returns NULL.

   Four, send the request

In Ajax, many requests to use XMLHttpRequest are initialized from an HTML event, such as a button click (onclick) or a keystroke (onkeypress) that invokes a JavaScript function. Ajax supports a variety of applications, including form checksums. Sometimes, you need to validate a unique form field before populating the other contents of the form. For example, you need to use a unique userid to register the form. If you do not use AJAX technology to validate this userid domain, the entire form must be populated and submitted. If the userid is not valid, this form must be resubmitted. For example, a form field corresponding to a catalog ID that requires a checksum 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 field. 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 invoke 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 that checks for and determines the appropriate creation method to use-before the object is created and returned.


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 argument to True, as shown above.
In this case, the call to the URL Validateform activates a servlet on the server side, but you should be able to note that the server-side technology is not fundamental; in fact, the URL may be a asp,asp. NET or PHP page or a Web service-it doesn't matter, as long as the page can return a response-indicating whether the Catalogid value is valid-you can. Because you are making an asynchronous call, you need to register a callback event handler that the XMLHttpRequest object will invoke-called when its readystate value changes. Remember that a change in 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 an HTTP GET method, you can call the Send () method without specifying the parameter or using the 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 calls a Doget () method that retrieves the Catalogid parameter value specified in the URL and checks its validity from a database.

This servlet in this example needs to construct a response sent to the client, and the 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 overloading 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 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 composed of plain text or XML, but a response can also be another 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 state. When the request completes loading (the readystate value is 4) and the response is complete (HTTP status is "OK"), you can invoke a JavaScript function to handle the response content. The following script is responsible for checking the corresponding value and calling a ProcessResponse () method when the response is complete.

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

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

var msg=xmlhttpreq.responsexml;

Using the 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 using the innerHTML attribute, 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

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 through data transfer without having to send a Web page to 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.


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.