Detailed description of XMLHttpRequest objects in AJAX Core

Source: Internet
Author: User

The XMLHttpRequest object is the core of AJAX functions. To develop an AJAX program, you must first understand the XMLHttpRequest object.

To understand the XMLHttpRequest object, you must first create the XMLHttpRequest object and create the XMLHttpRequest object in different browsers using different methods:

First, let's take a look at how IE creates the XMLHttpRequest object. method 1 ):

var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");  
// Use a newer version of IE to create an IE-compatible object Msxml2.XMLHTTP)
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
// Use older versions of IE to create IE-compatible Microsoft. XMLHTTP)

Mozilla, Opera, Safari, and most non-IE browsers use the following method. 2) create an XMLHttpRequest object:

var xmlhttp = new XMLHttpRequest();

In fact, Internet Explorer uses an object named XMLHttp, instead of the XMLHttpRequest object. Mozilla, Opera, Safari, and most non-Microsoft browsers use the latter, which is collectively referred to as the XMLHttpRequest object ). IE7 began to use the XMLHttpRequest object.

When creating an XMLHttpRequest object, if different browsers use incorrect methods, the browser reports an error and cannot use the object. Therefore, we need a method that is compatible with different browsers to create XMLHttpRequest objects:

Create an XMLHttpRequest object method compatible with multiple browsers

Var xmlhttp = false; // create a new variable request and assign a value of false. False is used as the judgment condition, indicating that the XMLHttpRequest object has not been created.
Function CreateXMLHttp (){
Try {
Xmlhttp = new XMLHttpRequest (); // try to create an XMLHttpRequest object. all browsers except IE support this method.
}
Catch (e ){
Try {
Xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP"); // use a newer version of IE to create an IE-compatible object Msxml2.XMLHTTP)
}
Catch (e ){
Try {
Xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP"); // use older versions of IE to create IE-compatible objects Microsoft. XMLHTTP ).
}
Catch (failed ){
Xmlhttp = false; // if the request fails, make sure that the request value is still false.
}
}
}
Return xmlhttp;
}
It is easy to determine whether the creation is successful.

If (! Xmlhttp ){
// An error occurred while creating the XMLHttpRequest object!
}
Else {
// Creation successful!
}

After creating the XMLHttpRequest object, let's take a look at the method, attributes, and the most important onreadystatechange event handle of this object.

Method:

Open () Description: Initialize HTTP request parameters, such as URLs and HTTP methods, but do not send requests.

Abort () Description: cancels the current response, closes the connection, and ends any pending network activities.

GetAllResponseHeaders () indicates that the HTTP response header is returned as an unparsed string.

GetResponseHeader () Description: return the value of the specified HTTP response header.

Send () Description: sends an HTTP request, uses parameters passed to the open () method, and optional request bodies passed to the method.

SetRequestHeader () Description: sets or adds an HTTP request to an opened but not sent request.

Attribute:

ReadyState indicates the status of the HTTP request.

ResponseText indicates that the response body received by the server does not include the header so far. or, if no data is received, it is a null string.

ResponseXML: the response to the request is parsed to XML and returned as a Document object.

Status description: The HTTP status code returned by the server.

StatusText: This attribute specifies the HTTP status code of the request by name instead of number.

Onreadystatechange is the event handle function called every time the readyState attribute changes.

Next, let's take a look at the XMLHttpRequest object from the process of sending a request and processing the request results.

Before sending a request, an XMLHttpRequest object is generated, and no more code is written.

Generate an XMLHttpRequest object

var xmlhttp = CreateXMLHttp();

After creating the XMLHttpRequest object, which website should we send the request to? Choose RSS on the homepage of the blog Park. How can I set the website address I want to request? Use the open () method.

Open (method, url, async, username, password)

This method has five parameters, what specific meaning can be viewed here: http://www.w3school.com.cn/xmldom/dom_http.asp
This is what we use.

XmlHttp. open ("get ","Http://www.cnblogs.com ", true);

The get parameter indicates that the get method is used. The second parameter is the target address, the blog homepage, and the third parameter indicates whether the get method is asynchronous. Of course, true is used. The specific parameter description can also go to the http://www.w3school.com.cn above read.

Okay. The target is set. How can I send it. Using the send () method?

The send (body) and send () methods have only one parameter, indicating the DOM object. This DOM object requires a lot of content to be described. Next time, we only need to write

Xmlhttp. send. Okay, I sent it. How can I handle the returned results? In this case, the most important thing about the XMLHttpRequest object is the onreadystatechange event handle. What do you mean? You need to describe the readyState of the XMLHttpRequest object. There are five readystates, which are represented by numbers 0 to 4.

Status Name Description
0 Uninitialized Initialization status. The XMLHttpRequest object has been created and is not called before open () or has been reset by the abort () method.
1 Open The open () method has been called, but the send () method has not been called. The request has not been sent.
2 Sent The Send () method has been called and the HTTP request has been sent to the Web server. No response is received.
3 Processing ing All Response Headers have been received. The response body starts receiving but is not completed.
4 Loaded The HTTP response has been fully received.

However, it should be noted that the status of the onreadystatechange event handle is different for different browsers. IE and FireFox can process 1 to 4, while Safari can process 2 to 4, opera can process statuses 3 and 4. The status of 0 is basically useless, because the open () method will be called immediately after the XMLHttpRequest object is created, and the status will change to 1 at this time, of course, unless you want to determine whether the object has been canceled by abort (), this is still rare. In most cases, it is enough to determine whether 4 has been accepted.

Now that we understand that there are five states in readyState, we can simply process the returned results and change the status to different States, how can I tell the XMLHttpRequest object who will handle this change when its state changes. There are two ways to write, one is to use the anonymous method, the other is to specify the method, in fact, only different write and send, the role is the same, look at the Code:

Xmlhttp. onReadyStateChange = function (){
// Code for handling status changes
}
// Or
Xmlhttp. onReadyStateChange = getResult;
Function getResult (){
/// Code for handling status changes
}

By the way, the name of the handle is long. You can remember that on ReadyState Change indicates that the request is sent when the read status changes, and the processing method is also specified. How can you get the returned content, the responseText and responseXML attributes are available for use. responseXML is the returned object and needs to be parsed. Next, we will use responseText to see what is returned.

Alert (xmlhttp. responseText); // check whether the HTML code of the homepage is returned. You have succeeded.

The entire process is: Create an XMLHttpRequest object-> specify the Sending address and method-> send request-> specify the processing method and process the returned results.However, it should be noted that our normal thinking is like this, but the onreadystatechange event handle must be specified before sending, otherwise the status change event cannot be handled.

Therefore, we should follow the following process to remember: Create an XMLHttpRequest object-> specify the Sending address and sending method-> specify the processing method of status change-> send request, when the status of the request changes, the specified processing method is automatically called.
Okay. Let's take a look at the completed code.

Completed code


Var xmlhttp = false; // create a new variable request and assign a value of false. False is used as the judgment condition, indicating that the XMLHttpRequest object has not been created.
Function CreateXMLHttp (){
Try {
Xmlhttp = new XMLHttpRequest (); // try to create an XMLHttpRequest object. all browsers except IE support this method.
}
Catch (e ){
Try {
Xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP"); // use a newer version of IE to create an IE-compatible object Msxml2.XMLHTTP)
}
Catch (e ){
Try {
Xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP"); // use older versions of IE to create IE-compatible objects Microsoft. XMLHTTP ).
}
Catch (failed ){
Xmlhttp = false; // if the request fails, make sure that the request value is still false.
}
}
}
Return xmlhttp;
}
Xmlhttp = CreateXMLHttp ();
Xmlhttp. open ("get", "http://www.cnblogs.com", true );
Xmlhttp. onReadyStateChange = getResult;
Xmlhttp. send ();
Function getResult (){
If (xmlhttp. readyState = 4 ){
Alert (xmlhttp. responseText );
}
}

Everything seems okay, but have you ever thought about what if the HTML code fails during network transmission or the specified address fails. This requires the status attribute, that is, the HTTP status code returned by the server. When xmlhttp. status is 200, it indicates that the transmission process is complete and there is no error. What does the specific HTTP status code mean can go to the W3C organization website to see, address http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1.

Write the getResult () method as follows so that I think it is really OK.

 function getResult(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}

Well, I wrote so many simple things. It seems so cool. However, I think programming is very important to understand the basic content. Nowadays, many AJAX programs use many JS libraries and do not need to write such basic code directly. For example, if we use the famous jQuery, but if we have a good understanding of the basic things, then these libraries report errors, or if there is a problem, we can quickly know where the error is, make faster changes to make the program run normally.

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.