AJAX Summary (3), XMLHttpRequest Object



Blogger Blog: Stillwater Blog
This article is originally reproduced by the author.


This article introduces the knowledge of XMLHttpRequest objects. These include: the nature of the XMLHttpRequest object, the Http request and the Http response.

I. The Essence of XMLHttpRequest Object

To better understand the nature of the XMLHttpRequest object, we divide it into three parts. Seeing the name of a thing one thinks of its function,

XMLHttpRequest = XML + Http + Request 。

What is XML?

XML is designed to transmit and carry data information, not to represent or display data, while HTML is used to represent data, so the focus of XML is to explain what data is and carry data information. XML is widely used as a form of cross-platform interactive data, mainly for the content of data.
For example, XML defines structure, stores information, and transmits information. The following example is a small note sent to a large element, stored in XML. This XML document is just pure information tags, and the expansion of the meaning of these tags depends on the application program.

<?xml version="1.0"?>
< little note >
 Sender > Xiao Zhang </ Sender >
 Subject > Greetings </Subject >
 Morning, have you had your meal yet? </Specific content>
< little note >

What is Http?

HyperText Transfer Protocol (HTTP) is the most widely used network protocol on the Internet. HTTP was originally designed to provide a way to publish and receive HTML pages. Later in this article, the Http knowledge related to AJAX technology will be introduced in detail.

What is Request?

Request is translated into request, as we all know. But many people misunderstand that we can only send Http requests to servers with browsers (Chrome, Safari, IE). That’s not right. Let’s change our point of view and think from the server’s point of view. When the server receives Http requests from all over the world, it does not know who is on the opposite side of the screen. It may be you surfing the Internet, or it may be just a web crawler, or even an XMLHttpRequest object in our AJAX program.

Back to our question, what is the nature of the XMLHttpRequest object?

Http is an object that can send Http requests, process Http responses, and exchange data asynchronously with servers. Its core is Http.

So if you want to understand XMLHttpRequest object in depth, you need to learn some knowledge about Http. Look down, please.

Http request

An Http request consists of four parts:

  • Http request method (GET, POST, DELETE, PUT)

  • The URL being requested (/home/index.html)

  • Request header (optional)

  • Request body (optional)

After creating the XMLHttpRequest object, the next step in initiating the Http request is to call the open () method of the XMLHttpRequest object to specify two essential parts of the request: the request method and the URL.

Request.open ("GET", / home/index.html); // request method: GET, URL:/ home/index.html

The first parameter of open () specifies the Http request method, usually matching the Http protocol with uppercase letters. The second parameter of open () is the URL, which is the main content of the request. If there is a request header, the next step in the request process is to set it up. For example, POST requests require “Content-type”.


The last step in using XMLHttpRequest to initiate a Http request is to specify the request body (optional) and send it to the server. Use the send () method as follows:


GET requests have no principal, so you should pass null or omit this parameter.

Each part of the Http request has a specified order: the request method and the URL arrive first, then the request header, and finally the request body. The order in which the XMLHttpRequest method is invoked must match the order in which the Http request is made. For example, the setRequestHeader () method must be called after the open () method and before the send () method, otherwise an exception will be thrown.

Example: Send plain text to server by POST method

function postMessage(msg){
    Var request = new XMLHttpRequest (); // Create a new request
    Request.open ("POST", "log.php"); and // Send scripts to the server with POST
    Request.setRequestHeader ("Content-type", "text/plain; charset = UTF-8"); //request header settings
    Request.send(msg);//Send MSG as the main body of the request
    }// Since no response function is specified, we will ignore any response.

Http response

The Http response returned by the server consists of three parts:

  • A status code consisting of numbers and text to show the success or failure of a request

  • Response head

  • Response subject

We can get the three parts of the above response through the attributes and methods of the XMLHttpRequest object.

  • The status and status Text attributes return the Http status code in the form of numbers and text.

  • Response headers can be queried using getResponseHeader () and getAllResponseHeaders ().

  • The response body can get the text form from the responseText attribute and the Document form from the responseXML attribute.

  • ReadyState is an integer that specifies the status of the Http request.

Table: ReadyState value of XMLHttpRequest

constant value Meaning
UNSENT 0 Open () not yet called
OPENED 1 Open () has been called
HEADERS_RECEIVED 2 Receive header information
LOADING 3 Receive the response subject
DONE 4 Response completion

To listen for readystatechange events, set the event handler to the onreadystatechange property of the XMLHttpRequest object.

Example: onreadystatechange to obtain the Http response

// Send an Http GET request to get the content of the specified URL
// When the response arrives successfully, verify that it is plain text
// If so, pass it to the specified callback function
function getText(url,callback){
    Var request = new XMLHttpRequest (); // Create a new request
    Request. open ("GET", url); // Specify the URL to be retrieved
    Request. onreadystatechange = funciton () {// Define event handler
        If (request. readyState=== 4 & & request. status=== 200 {/// If the request is completed, it is successful
            var type = request.getResponseHeader("Content-Type");
            If (type. match (/^ text /)/// Make sure the response is text
                Callback (request. responseText); // Pass it to the callback function
        Request. send (null) // Send the request immediately

Four, summary

This paper introduces that the essence of XMLHttpRequest object is an object that can send Http requests, process Http responses, and exchange data asynchronously with servers. Its core is Http. Then it introduces the specific content of Http request and response. Http requests include methods, URLs, request headers, and request bodies. Http response package: state code, response head and response body.


[1] Wikipedia
[2] JavaScript Authoritative Guide

Recommended Today

The construction tool of C ා

What’s the motivation for writing this article? Why do you want to study the build tool (see. Csproj), create a new C project with visual studio IDE, and click build to run it? A: please refer to this_minutes_before_coding. I call it “engineering.”. Engineering development is not just about opening IDE and creating new projects. It […]