What I’m going to talk about is very basic, so experts shouldn’t read it. If you read it, please give me your opinion. Novices or people who don't know much about low-level knowledge can read it to help their understanding and memory.
The XMLHttpRequest object is the core of the AJAX function. To develop an AJAX program, you must start by understanding the XMLHttpRequest object.
To understand the XMLHttpRequest object, start by creating the XMLHttpRequest object. Creating XMLHttpRequest objects in different browsers uses different methods:
first look at the method of IE creating 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 an older version of IE to create an IE-compatible object (Microsoft.XMLHTTP)
Mozilla, Opera, Safari and most non-IE browsers use the following method (Method 2) to create XMLHttpRequest objects:
var xmlhttp = new XMLHttpRequest();
Internet Explorer actually uses an object called XMLHttp instead of the XMLHttpRequest object, which Mozilla, Opera, Safari, and most non-Microsoft browsers use (hereinafter collectively referred to as the XMLHttpRequest object). IE7 also started to use the XMLHttpRequest object.
If different browsers use incorrect methods when creating the XMLHttpRequest object, the browser will report an error and the object cannot be used. So we need a method to create an XMLHttpRequest object that is compatible with different browsers:
Create an XMLHttpRequest object method that is compatible with multiple browsers
var xmlhttp = false; //Create a new variable request and assign it a value of false. Use false as the judgment condition, which means that the XMLHttpRequest object has not been created yet.
function CreateXMLHttp(){
try{
xmlhttp = new XMLHttpRequest(); //Try to create an XMLHttpRequest object. 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 an older version of IE to create an IE-compatible object (Microsoft.XMLHTTP).
}
catch (failed){
xmlhttp = false; //If it fails, ensure that the value of request is still false.
}
}
}
return xmlhttp;
}
It is very simple to judge whether the creation is successful
if (!xmlhttp){
//Failed to create XMLHttpRequest object!
}
else{
//Created successfully!
}
After creating the XMLHttpRequest object, let's take a look at the methods, properties and the most important onreadystatechange event handler of this object.
Method:
open() Description: Initialize HTTP request parameters, such as URL and HTTP method, but do not send the request.
abort() Description: Cancel the current response, close the connection and end any pending network activity.
getAllResponseHeaders() Description: Return HTTP response headers as unparsed strings.
getResponseHeader() Description: Returns the value of the specified HTTP response header.
send() Description: Sends an HTTP request, using the parameters 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.
Attributes:
readyState Description: The status of the HTTP request.
responseText Description: The response body (excluding headers) received by the server so far, or an empty string if no data has been received.
responseXML Description: The response to the request, parsed into XML and returned as a Document object.
status Description: HTTP status code returned by the server.
statusText Description: This attribute specifies the HTTP status code of the request using a name instead of a number.
onreadystatechange is the event handler function called every time the readyState property changes.
Let's understand the XMLHttpRequest object from the process of sending a request and processing the request results.
Naturally, an XMLHttpRequest object is generated before sending the request. There is no need to write more code if it is already there.
Generate an XMLHttpRequest object
var xmlhttp = CreateXMLHttp();
After creating the XMLHttpRequest object, which website do we want to send the request to? Let’s choose the RSS on the homepage of the blog park. So how do I set the website address I want to request? Use the open() method.
open(method, url, async, username, password)
This method has 5 parameters. You can see the specific meaning 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 means using the get method. The second one is naturally the target address, the homepage of the blog park. The third one means whether it is asynchronous. Of course we use true. Specific parameter descriptions can also be found at http://www.w3school.com.cn .
Okay, the goal is set, how to send it. Use send() method.
send(body), the send() method has only one parameter, which represents the DOM object. This DOM object needs to explain a lot. Next time, today we only need to write
xmlhttp.send(null);
That's it. Okay, it's sent, so how to deal with the returned results? At this time, the most important thing of the XMLHttpRequest object is used, which is the onreadystatechange event handle. What does it mean? Then we need to explain the readyState of the XMLHttpRequest object. There are 5 states of readyState, represented by numbers 0 to 4 respectively.
Status Name Description
0 Uninitialized Initialization state. The XMLHttpRequest object has been created (before open() was called) or 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 The Sent Send() method has been called and the HTTP request has been sent to the Web server. No response received.
3 Receiving All response headers have been received. Response body started to be received but not completed.
4 Loaded HTTP response has been fully received.
However, it should be noted that the states that different browsers can handle in the onreadystatechange event handle are not consistent. IE and FireFox can handle states 1 to 4, while Safari can handle states 2 to 4, and Opera can handle states 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 become 1 at this time, unless of course you want to determine whether the object has been canceled by abort(), but this situation is still very common. few. In most cases, it is enough to determine whether the status is 4 (accepted and completed).
Okay, I understand that readyState has 5 states. Then the processing return result is to see if the state changes to different states and we can do different processing. How to tell the XMLHttpRequest object who should handle the change when the state changes. There are two ways of writing, one is to use anonymous method, the other is to specify method. In fact, they are just different writing methods with the same effect. Take a look at the code:
xmlhttp.onReadyStateChange = function (){
//Code to handle status changes
}
//or
xmlhttp.onReadyStateChange = getResult;
function getResult(){
///Code to handle status changes
}
//By the way, the name of the handle is relatively long. You can remember it like this. On ReadyState Change means that the request was sent when the reading state changed, and the processing method is also specified. How to get the returned content? There are two attributes: responseText and responseXML. For use, responseXML is the return object and needs to be parsed. I will talk about it later. Here, use responseText first to see what is returned.
alert(xmlhttp.responseText); //See if the HTML code of the homepage is returned. It’s you who succeeds.
The whole process is: create XMLHttpRequest object -> specify the sending address and sending method -> send the request -> specify the processing method and process the return result. But it should be noted that our normal understanding is this, but the specified processing method of the onreadystatechange event handle needs to be specified before sending, otherwise the state change event cannot be processed.
So we should remember it according to the following process: create XMLHttpRequest object -> specify the sending address and sending method -> specify the status change processing method -> send the request. After the request is sent, the specified processing method will be automatically called when the status changes.
Okay, let's take a look at the completed code.
completed code
var xmlhttp = false; //Create a new variable request and assign it a value of false. Use false as the judgment condition, which means that the XMLHttpRequest object has not been created yet.
function CreateXMLHttp(){
try{
xmlhttp = new XMLHttpRequest(); //Try to create an XMLHttpRequest object. 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 an older version of IE to create an IE-compatible object (Microsoft.XMLHTTP).
}
catch (failed){
xmlhttp = false; //If it fails, ensure that the value of request is still false.
}
}
}
return xmlhttp;
}
xmlhttp = CreateXMLHttp();
xmlhttp.open("get"," http://www.cnblogs.com",true );
xmlhttp.onReadyStateChange = getResult;
xmlhttp.send(null);
function getResult(){
if(xmlhttp.readyState == 4){
alert(xmlhttp.responseText);
}
}
Everything seems to be OK, but have you ever thought about what would happen if the HTML code goes wrong during network transmission, or the address we specify becomes invalid. At this time, you need to use the status attribute, which is the HTTP status code returned by the server. When xmlhttp.status is equal to 200, it means that the transmission process is complete and error-free. For the specific meaning of the HTTP status code, you can go to the W3C organization website to see the address http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1 .
I think it's really OK to write the getResult() method as follows.
function getResult(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
Okay, something that was originally quite simple seems to be very wordy after I have written so much about it. However, I think it is very important to understand the basic content of programming. Nowadays, many JS libraries are used to develop AJAX programs, and there is no 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 know where the error is very quickly, and make changes faster to make the program run normally. .