Detailed Ajax core--xmlhttprequest object (top)

Source: Internet
Author: User

I would like to say that the content is very basic content, the master will be free to read, if you see a welcome to the point of opinion Ah. Beginners or people who are not very knowledgeable about the lower levels can look at it and help them understand and remember.

The XMLHttpRequest object is the core of AJAX functionality, and the development of an AJAX program must begin with an understanding of the XMLHttpRequest object.

Understanding the XMLHttpRequest object begins with creating a XMLHttpRequest object, using different methods for creating XMLHttpRequest objects in different browsers:

First look at the way IE creates XMLHttpRequest objects (Method 1):

var xmlhttp = new ActiveXObject ("Msxml2.xmlhttp"); Create IE-compatible objects with a newer version of IE (msxml2.xmlhttp)
var xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); Use older versions of IE to create IE-compatible objects (MICROSOFT.XMLHTTP)

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

var xmlhttp = new XMLHttpRequest ();

In fact, Internet Explorer uses an object named XMLHttp instead of a XMLHttpRequest object, while Mozilla, Opera, Safari, and most non-Microsoft browsers use the latter (collectively, the XML HttpRequest object). IE7 started using the XMLHttpRequest object as well.

When creating a XMLHttpRequest object, the browser will error if different browsers use the incorrect method, and the object cannot be used. So we need a way to create XMLHttpRequest objects that are compatible with different browsers:

Create a XMLHttpRequest object method that is compatible with multiple browsers

It's easy to decide if you're creating a success.

if (!xmlhttp) {
Failed to create XMLHttpRequest Object!
}
else{
Create success!
}

The XMLHttpRequest object is created, so let's take a look at the object's methods, properties, and the most important onreadystatechange event handle.

Method:

    • Open () Description: Initializes the HTTP request parameters, such as URLs and HTTP methods, but does not send the request.
    • Abort () Description: Cancels the current response, closes the connection, and ends any pending network activity.
    • getAllResponseHeaders () Description: Returns the HTTP response header as an unresolved string.
    • getResponseHeader () Description: Returns the value of the specified HTTP response header.
    • Send () Description: Sends an HTTP request, using the arguments passed to the open () method, and the optional request body passed to the method.
    • setRequestHeader () Description: Sets or adds an HTTP request to an open, but not sent, request.

Property:

    • ReadyState Description: The status of the HTTP request.
    • ResponseText Description: The response body (not including the header) received by the server so far, or an empty string if the data has not yet been received.
    • Responsexml Description: Response to the request, parsing to XML and returning as the Document object.
    • Status Description: The HTTP status code returned by the server.
    • StatusText Description: This property specifies the status code of the requested HTTP with a name rather than a number.
      onReadyStateChange is the event handle function that is called every time the ReadyState property is changed.

Here's a look at the XMLHttpRequest object from the process of sending the request and processing the request result.

It is natural to generate a XMLHttpRequest object before sending the request, and there is no more writing on the code.

Generate a XMLHttpRequest Object

var xmlhttp = createxmlhttp ();

Create a good XMLHttpRequest object, then we have to send the request to which site, choose the blog Home page RSS. How to set the address of the website I want to request, use the open () method.
Open (method, URL, async, username, password)
The method has 5 parameters, specifically what the meaning can be seen here: http://www.w3school.com.cn/xmldom/dom_http.asp
That's what we're using.

Xmlhttp.open ("Get", "http://www.cnblogs.com", true);

The get parameter is represented by the Get method, the second nature is the destination address, the blog home page, the third is to indicate whether it is asynchronous, we certainly use true. The detailed parameter explanation also can go to http://www.w3school.com.cn above to see.
Well, the goal is set, how to send it. Use the Send () method.
Send (body), the Send () method has only one parameter, representing the DOM object, this DOM object needs to explain a lot of content, next time, today we just write

Xmlhttp.send (NULL);

You can do it. OK, send, then how to deal with the results of the return, this time to use the XMLHttpRequest object is the most important thing, that is the onreadystatechange event handle. What does that mean, then need to explain the XMLHttpRequest object's readystate, ReadyState has 5 kinds of States, respectively with the number 0 to the 4来 expression.

Status        name               description  
0      uninitialized       initialization state. The XMLHttpRequest object has been created (before open () is called) or has been reset by the Abort () method.  
1      open          The   open () method was called, but the Send () method was not called. The request has not been sent yet.  
2      sent          The    send () method was called and the HTTP request was sent to the WEB server. The response was not received.  
3      receiving       All the response headers have been received. The response body begins to receive but is not completed.  
4      loaded          The HTTP response has been fully received.

However, it should be noted that the onReadyStateChange event handle is not consistent with different browsers, IE and Firefox can handle 1 to 4, and Safari can handle 2 to 4 status, Opera can handle 3, 42 state. The state of 0 is basically useless, because the open () method is called immediately after the XMLHttpRequest object is created, and the state becomes 1, unless you want to determine whether the object has been canceled by abort (), but this is still rare. In most cases it is enough to judge whether 4 (already accepted) is the state.
Okay, I got it. ReadyState has 5 states, and the processing return result is to see the state change to a different state we do different processing can be, how to tell the XMLHttpRequest object state changes when to let who handle the change? There are two ways to write, one is to use anonymous methods, the other is to specify the method, in fact, just different writing, the role is the same, look at the code:

Xmlhttp.onreadystatechange = function () {
Code to handle state changes
}
Or
Xmlhttp.onreadystatechange = GetResult;
function GetResult () {
Code to handle state changes
}
By the way, the name of the handle is longer, so you can remember that on the ReadyState change indicates when the read state changes

Request sent, also specify the processing method, how to get the contents of the return, there are ResponseText and responsexml two properties to use, Responsexml is the return object, need to parse, and then again, here first with ResponseText, See what's returned.

alert (Xmlhttp.responsetext); See if it returns the HTML code of the homepage. It was you who succeeded.

The entire process is: Create a XMLHttpRequest object, specify the send address and send method, send request, specify the processing method and process the return result. However, it is important to note that our normal way of thinking is this, but the onreadystatechange event handle specifies that the processing method needs to be specified before it is sent, otherwise the state change event cannot be processed.

So we should follow the following process to remember: Create XMLHttpRequest object, specify send address and send method, specify the state change processing method, send the request, the request sent after the state changes will automatically invoke the specified processing method.
Well, look at the finished code.

the finished code

Looks like everything OK, but have you ever thought, if the HTML code in the network transmission error, or we specify the address of the failure will be what? The Status property, the HTTP status code returned by the server, is required at this time. Xmlhttp.status equals 200 indicates that the transfer process is complete without errors. Specific HTTP status code what meaning can go to the Web site to see the website, address http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1.
Write the GetResult () method below so that I can really feel OK.

function GetResult () {
if (xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {
alert (Xmlhttp.responsetext);
}
}

Well, a very simple thing, I wrote so much, as if very wordy. But I think the programming to the basic content of the understanding is very important, now many times the development of AJAX programs are using a lot of JS Library, do not need to write such basic code directly. such as using the famous jquery, but if we have a good understanding of the underlying things, then these libraries report errors, or there are problems we can very quickly know where the wrong, faster to make changes to make the program work.

Category: AJAX

Detailed Ajax core--xmlhttprequest object (top)

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.