A detailed description of XMLHttpRequest objects in Ajax

Source: Internet
Author: User

The XMLHttpRequest object is at the heart of Ajax technology. In Internet Explorer 5, the XMLHttpRequest object is introduced as an ActiveX object, called XMLHTTP, which is a technique that supports asynchronous requests. Later, Mozilla, Netscape, Safari, Firefox, and other browsers also provided the XMLHttpRequest class, although these browsers provided the XMLHttpRequest class, However, they do not create the XMLHttpRequest class in the same way. XMLHttpRequest allows us to use JavaScript to make requests to the server and handle the response without blocking other user actions.

Interacting with the server without refreshing the page is the biggest feature of Ajax. This important feature is mainly attributed to the XMLHttpRequest object. Using the XMLHttpRequest object enables a Web application to respond to a user's interaction with the server in a timely manner, like a Windows application, without the need for page refreshes or jumps, and the ability to perform a series of data processing that can shorten the user's waiting time. It also reduces the load on the server side.

XMLHttpRequest objects are now supported by most browsers, so there is generally no problem when developing Web applications using AJAX technology. However, when developers decide to use Ajax technology to develop, they still need to consider what browser users will use to access the site, although there are few browsers that do not support XMLHttpRequest objects.

Before you can use the XMLHttpRequest object to send a request to the server and process the response, you must first create a XMLHttpRequest object with JavaScript and then make a request with the server and receive the data returned by the server. Since XMLHttpRequest is not a standard, there are several ways to use JavaScript to create instances of XMLHttpRequest. Internet Explorer implements XMLHttpRequest as an ActiveX object, and other browsers (such as Firefox, Safari, and Opera) implement it as a native JavaScript object. Because of these differences, JavaScript code must contain relevant logic to use ActiveX technology or to create an instance of XMLHttpRequest using the native JavaScript object technology.

Because XMLHttpRequest objects are created differently in different browsers, the browser needs to be judged before the XMLHttpRequest object is created in the program. The way you use detailed code to differentiate browser types is not only a large amount of code, but also inconvenient and inflexible. Here we can change the idea to solve, only need to check whether the browser provides support for ActiveX objects. If your browser supports ActiveX objects, you can use ActiveX to create XMLHttpRequest objects. Otherwise, you need to use native JavaScript object technology in your program to create it. The following code shows the programming method of using JavaScript code in different browsers to create XMLHttpRequest objects.

#001 function createxmlhttprequest ()

#002 {

#003     var xmlreq = false;

#004    if (window. ActiveXObject)

#005    {

#006         xmlreq = new ActiveXObject ("Microsoft.XMLHTTP");

#007    }

#008    else if (window. XMLHttpRequest)

#009    {

#010         xmlreq = new XMLHttpRequest ();

#011    }

#012    return XMLreq;

#013}

As we see from the above code, the process of creating a XMLHttpRequest object is simple. First, a variable xmlreq is created in the Createxmlhttprequest () method to hold a reference to the object and set its default value to False. Then in this method, by simple judgment, determine exactly what method is used to create the object. Because the user is using a different browser type, the code window. ActiveXObject may return an object, or it may return null. The IF condition statement determines whether the browser is capable of supporting ActiveX controls based on the returned results, and accordingly learns if the browser is IE or another browser type. If the user is determined to be using IE, the XMLHttpRequest object is created by instantiating an instance of ActiveXObject. When you use this method, the parameter string indicates what type of ActiveX object to create. In this example, the parameter is Microsoft.XMLHTTP, which indicates that an instance of XMLHttpRequest needs to be created.

If window. ActiveXObject returns NULL, indicating that the user is using a browser that does not support ActiveX objects, and that the program performs the actions specified by the Else statement. First, determine whether the browser implements XMLHttpRequest as a local JavaScript object. If a window exists. XMLHttpRequest, the XMLHttpRequest object is created. Finally, the XMLREQ variable is returned and the process of creating the XMLHttpRequest object is completed.

Because JavaScript has a dynamic type of feature, and the XMLHttpRequest object is compatible with implementations on different browsers, all of the properties and methods of the XMLHttpRequest instance can be accessed in the same way, regardless of the method the instance creates. This greatly simplifies the development process, and there is no need to write browser-specific logic in JavaScript.

XMLHttpRequest properties of an object

The XMLHttpRequest object provides many properties that need to be used frequently when working with XMLHttpRequest, as shown in the following table:

Property

Describe

onReadyStateChange

This event handler is triggered when each state changes, and a JavaScript function is usually called

ReadyState

Status of the request

ResponseText

The response of the server, expressed as a string

Responsexml

The response of the server, expressed as XML, can be parsed as a DOM object

Status

HTTP status of the server

StatusText

Corresponding text for HTTP status

Let's take a look at the detailed descriptions of these properties and events.

1. ReadyState Properties

When an HTTP request is sent to the server, the XMLHttpRequest object goes through a number of States. Waits until the request is processed, and then it receives a response. Since then, the script responds correctly to various states, and the XMLHttpRequest object exposes a ReadyState property that describes the current state of the object, as shown in the following table:

readyState Take value

Describe

0

Describes an "uninitialized" state. At this point, a XMLHttpRequest object has been created, but it 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 through the Send () method, but a response has not yet been received.

3

Describes a "receiving" state. At this point, the 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 this point, the response has been fully received.

2. onReadyStateChange Properties

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

3. ResponseText Properties

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.

4. Responsexml Properties

This 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 that the MIME (media) 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 a document interface type object that describes the parsed document. 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.

5. Status Property

This 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). When the value of readystate is less than 3 o'clock attempting to access the status value throws an exception. For example: Status equals 200 indicates success, 404 means no resource found.

6. StatusText Properties

This 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.

Methods for XMLHttpRequest Objects

The following table shows some of the commonly used methods of the XMLHttpRequest object, where the description section describes the role and significance of these methods.

Method

Describe

Abort ()

Stop the current request

getAllResponseHeaders ()

Returns all corresponding headers for the HTTP request as key/value pairs.

getResponseHeader ("header")

Returns the string value of the specified header.

Open ("Method", "url")

Establish a call to the server. The method parameter can be get, post, or put, and the URL parameter can be a relative URL or an absolute URL. This method also includes 3 optional parameters.

Send (content)

Sends a request to the server.

setRequestHeader ("header", "value")

Sets the specified header to the provided value, and the open () method must be called before any headers can be set.

Let's look at the use of these methods in more detail.

1. Abort () method

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

2. Open () method

This method is used to establish a connection to the server. Its complete method parameter is open (string method,string uri,boolean asynch,string username,string password), where the first two parameters are necessary, followed by three for optional parameters.

The method parameter is required to specify the HTTP method (Get,post,put,delete or head) used 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 resolved to an absolute URI. In other words, if you use a relative URI, it will be parsed in the same way as a URI relative to the browser resolution. The Asynch parameter specifies whether the request is asynchronous, and the default value is true. In order to send a synchronous request, this parameter needs to be set to false. But the biggest advantage of Ajax technology is the invocation, so if this parameter is set to False, the meaning of using the XMLHttpRequest object will be lost. 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.

3. Send () method

After you have prepared a request by calling the open () method, you need to send the request to the server. The Send () method can be called 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 Asynch 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 that can contain data of a mutable type. Typically, it is used and sent 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 content parameter in the Send (content) method is string, then the data is encoded as UTF-8. If the data is of document type, the data will be serialized using the encoding specified by data.xmlencoding.

Note that the request is made after calling this method, so the setting for the XMLHttpRequest object needs to be done before calling this method. In addition, for that parameter in the Send () method, although it is optional, it is best not to omit this parameter when it is not necessary to send the data, it should be set to NULL, otherwise there will be an error in Firefox.

4. setRequestHeader ("header", "Value") method

This method is used to set the requested header information. When the readystate value is 1 o'clock, this method can be called after the Open () method is called. Otherwise, an exception is obtained.

5. getResponseHeader ("header") method

This 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.

6. getAllResponseHeaders () method

The 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.

A detailed description of XMLHttpRequest objects in Ajax

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.