This is the 15th day of my participation in the More text Challenge. For more details, see more text Challenge

An overview of the

AJAX is an acronym for Asynchronous JavaScript and XML, which means performing Asynchronous network requests in JavaScript.

AJAX is not a new technology, but rather a term coined in 2005 by Jesse James Garrett to describe a ‘new’ approach 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 currently more commonly used than XML due to its many advantages, such as being lighter in weight and being part of Javascript. Both JSON and XML are used to package information in the AJAX model.

The advantage of AJAX

Traditional web pages (which do not use AJAX) must reload the entire page if they need to update their content.

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

The XMLHttpRequest object

The XMLHttpRequest (XHR) object is used to interact with the server. XMLHttpRequest allows you to request a specific URL and retrieve data without refreshing the page. This allows pages to update parts of the page without affecting user action. XMLHttpRequest is used extensively in AJAX programming.

How AJAX works

Its basic working principle through the following steps:

  1. The client sends the request, which goes to XHR.
  2. XHR submits the request to the service.
  3. The server processes services.
  4. The server responds with data to the XHR object.
  5. The XHR object receives data, which is written to the page by JavaScript.

AJAX creation steps

Based on how AJAX works, its creation steps mainly include:

  1. Create the XMLHttpRequest object, that is, create an asynchronous call object.
  2. Creates a new HTTP request and specifies the method, URL, and authentication information for the HTTP request.
  3. Sets a function that responds to changes in HTTP request status.
  4. Send an HTTP request.
  5. Gets the data returned by the asynchronous call.
  6. Local refresh using JavaScript and DOM.

Concrete use of AJAX

Here’s the complete process for using AJAX.

1. Create the XMLHttpRequest object

const request = new XMLHttpRequest();
Copy the code

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 XMLHttpReques t object’s open() method, which has the following syntax code:

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

Parameter analysis:

  • methodHTTP methods to use, such as “GET”, “POST”, “PUT”, “DELETE”, and so on.
  • urlRepresents the URL to which the request is to be sent.
  • Async (Optional)An optional Boolean parameter indicating whether to perform the operation asynchronously. Defaults to 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 (optionalUser name used for authentication. The default value is NULL.
  • Password (Optional)Password used for authentication. The default value is NULL.

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

After creating the HTTP request, you should be ready to send the HTTP request to the Web server. However, the purpose of sending an HTTP request is to receive the data returned from the server. The XMLHttpRequest object goes through the following five states:

  • Uninitialized state. When the XMLHttpRequest object is created, the object is in an uninitialized state, and the XMLHttpRequest object’s readyState property has a value of 0.
  • Initialization state. When an HTTP request is created using the open() method after the XMLHttpRequest object has been created, the object is in an initialized state. The XMLHttpRequest object’s readyState property has a value of 1.
  • Sending data status. After initializing the XMLHttpRequest object, the object is in the sending state when the send() method is used to send data, and the XMLHttpRequest object’s readyState property has a value of 2.
  • Receiving data status. After the Web server has received and processed the data, it sends the returned results to the client. At this point, the XMLHttpRequest object is in the receiving state, and the XMLHttpRequest object’s readyState property has a value of 3.
  • Complete state. After receiving the data, the XMLHttpRequest object enters the completed state, at which point the XMLHttpRequest object’s readyState property has a value of 4. At this point, the received data is stored in the memory of the client computer and can be obtained using the responseText property or responseXml property.

In general, the values of the readyState attribute are as follows:

  • 0 (uninitialized) or (request not initialized)
  • 1 (loading) or (server link established)
  • 2 (load successful) or (request accepted)
  • 3 (interaction) or (Processing request)
  • 4 (complete) 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. The value of status is 0 until the request completes. Note that if XMLHttpRequest fails, the browser returns status of 0:

  • UNSENT 0
  • OPENED 0
  • LOADING 200
  • DONE 200
var xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); / / readyState is 0

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

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

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

xhr.send(null);
Copy the code

Only after the XMLHttpRequest object completes the above five steps can the data returned from the server be retrieved. Therefore, to get the data returned from the server, you 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}}Copy the code

4. Send an HTTP request

XMLHttpRequest.send(data);
Copy the code

The end of the

Finally, attach a simple full 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>
Copy the code

~

~

To finish this article

~

Learn interesting knowledge, make interesting friends, and create interesting souls!

Everybody is good! I am the author of “programming Samadhi” hermit King, my public number is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!

Both knowledge and skill, internal force and external work, both theory and practice should grasp, both hands should be hard!