An overview of the

AJAX is an acronym, and its full name is Asynchronous JavaScript and XML, which means Asynchronous network requests executed using JavaScript.

Ajax is not a new technology, but rather a new term introduced in 2005 by Jesse James Garrett to describe a ‘new’ approach to using a collection of existing technologies, including:

  • HTML or XHTML
  • CSS
  • JavaScript
  • DOM
  • XML
  • XSLT
  • XMLHttpRequest

Although X stands for XML in Ajax, JSON is now more commonly used than XML due to its many advantages, such as being lighter and being part of JavaScript. Both JSON and XML are used to package information in an Ajax model.

The advantage of AJAX

Traditional web pages (which do not use Ajax) require reloading the entire page if you need to update content.

Ajax enables web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that you can update parts of a Web page without reloading the entire page.

The XMLHttpRequest object

The XMLHttpRequest (XHR) object is used to interact with the server. XMLHttpRequest allows you to retrieve data by requesting a specific URL without refreshing the page. This allows the page to update parts of the page without affecting the user’s actions. XMLHttpRequest is widely used in Ajax programming.

How Ajax works

Its working principle basically goes through the following steps:

  1. The client sends the request, which is handed to XHR.
  2. XHR submits the request to the service.
  3. The server does business processing.
  4. The server response data is handed over to the XHR object.
  5. The XHR object receives the data, which is written to the page by JavaScript.

The Ajax creation steps

Depending on how Ajax works, the steps to create it mainly include:

  1. Create an XMLHttpRequest object, that is, an asynchronous invocation object.
  2. Creates a new HTTP request, specifying the method, URL, and validation information for the HTTP request.
  3. Sets a function that responds to a change in the state of an HTTP request.
  4. Send an HTTP request.
  5. Gets the data returned by the asynchronous call.
  6. Use JavaScript and DOM to implement a partial refresh.

A concrete use of Ajax

Here’s the complete process of using Ajax.

1. Create XMLHttpRequest object

const request = new XMLHttpRequest();

2. Create a new HTTP request and specify the method, URL, and authentication information of the HTTP request

HTTP requests can be created using the open() method of the XMLHttpQUES T object, which has the following syntax code:

request.open(method, url, async, user, password);

Parameter analysis:

  • methodHTTP methods to use, such as “GET”, “POST”, “PUT”, “DELETE”, etc.
  • urlRepresents the URL to which the request is to be sent.
  • Async (optional)An optional Boolean parameter that indicates whether an operation should be performed asynchronously. Default is true. If the value is false, the send() method does not return until a reply is received. If true, notification of completed transactions is available to event listeners. This must be true if the multipart property is true, otherwise an exception will be thrown.
  • The user (optionalThe user name used for authentication purposes. Default is null.
  • Password (optional)Password for authentication purposes, default to null.

3. Set the function that responds to the HTTP request state change and the server return information function

Once you have created the HTTP request, you should be ready to send the HTTP request to the Web server. However, the purpose of an HTTP request is to receive the data returned from the server. From the creation of the XMLHttpRequest object, to the sending and receiving of data, the XMLHttpRequest object goes through the following five states:

  • Uninitialized state. When the XMLHttpRequest object is created, it is in an uninitialized state, and the readyState property of the XMLHttpRequest object has a value of 0.
  • Initialize the state. The XMLHttpRequest object is initialized when the HTTP request is created using the open() method after the object is created. At this point, the readyState property of the XMLHttpRequest object has a value of 1.
  • Send data status. After the XMLHttpRequest object is initialized, the object is in the send data state when the send() method is used to send data, and the readyState property of the XMLHttpRequest object has a value of 2.
  • Receive data state. After the Web server has received and processed the data, it sends the result back to the client. At this point, the XMLHttpRequest object is in the receiving state, and the readyState property of the XMLHttpRequest object is 3.
  • Complete state. After receiving data, the XMLHttpRequest object enters the complete state. At this time, the readyState property value of the XMLHttpRequest object is 4. At this point, the received data is stored in the memory of the client computer. You can use the responseText property or the responseXML property to retrieve the data.

In general, the readyState property has the following values:

  • 0 (uninitialized) OR (request not initialized)
  • 1 (loading) or (server link established)
  • 2 (successfully loaded) or (request accepted)
  • 3 (interaction) OR (processing request)
  • 4 (Completed) OR (Request completed and response ready)

The read-only property XMLHttpRequest.status returns the numeric status code in the XMLHttpRequest response. The value of status is an unsigned short integer. The status value is 0 before the request completes. It’s worth noting that if XMLHttpRequest fails, the browser returns a status of 0:

  • The letter was UNSENT
  • OPENED (OPENED) 0
  • Loading 200
  • I’ve DONE 200
var xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState 为 0

xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState 为 1

xhr.onprogress = function () {
    console.log('LOADING', xhr.readyState); // readyState 为 3
};

xhr.onload = function () {
    console.log('DONE', xhr.readyState); // readyState 为 4
};

xhr.send(null);

Only after the XMLHttpRequest object has completed the five steps above can the data returned from the server be retrieved. Therefore, in order to retrieve the data returned from the server side, we must first determine the state of the XMLHttpRequest object:

const xhr = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // do something here }}

4. Send an HTTP request

XMLHttpRequest.send(data);

The end of the

Finally, attach a simple complete Ajax instance:

<button id="ajaxButton" type="button">Make a request</button>

<script>
    var httpRequest;
    document.getElementById("ajaxButton").addEventListener('click', makeRequest);

    function makeRequest() {
        httpRequest = new XMLHttpRequest();

        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('GET', 'test.html');
        httpRequest.send();
    }

    function alertContents() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                alert(httpRequest.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }
    }
</script>

~

~

To finish this article

~

Learn interesting knowledge, meet interesting friends, build interesting soul!

Everybody is good! I am the author of “programming samadhi” hermit king, my public account is “programming samadhi”, welcome to pay attention to, I hope you give me more advice!

Pay equal attention to knowledge and skills, internal force and external work and repair, theory and practice both hands should grasp, both hands should be hard!