Ajax introduction and use of front-end JS

Time:2021-7-25

summary

AJAX is an abbreviation. Its full name isAsynchronous JavaScript and XML, which means asynchronous JavaScript and XML, i.eExecuting asynchronous network requests with JavaScript

AJAX is not a new technology, but a new term proposed by Jesse James Garrett in 2005 to describe a ‘new’ method using a collection of existing technologies, including:

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

Although X represents XML in Ajax, JSON is more commonly used than XML due to its many advantages, such as lighter weight and as part of JavaScript. Both JSON and XML are used to package information in the Ajax model.

Advantages of Ajax

Traditional web pages (without Ajax) must reload the whole web page if they need to update the content.

Ajax can make web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page.

XMLHttpRequest object

The XMLHttpRequest (XHR) object is used to interact with the server. With XMLHttpRequest, you can request a specific URL to get data without refreshing the page. This allows the web page to update the local content of the page without affecting the user’s operation. XMLHttpRequest is widely used in Ajax programming.

How Ajax works

Its working principle basically goes through the following steps:

  1. The client sends a request to XHR.
  2. XHR submits the request to the service.
  3. Server for business processing.
  4. The server sends the response data to the XHR object.
  5. The XHR object receives data and JavaScript writes the data to the page.

Ajax introduction and use of front-end JS

Ajax creation steps

According to the working principle of Ajax, its creation steps mainly include:

  1. To create an XMLHttpRequest object is to create an asynchronous call object.
  2. Create a new HTTP request and specify the method, URL and authentication information of the HTTP request.
  3. Sets the function that responds to changes in the status of HTTP requests.
  4. Send HTTP request.
  5. Gets the data returned by the asynchronous call.
  6. Use JavaScript and DOM to implement local refresh.

Specific use of Ajax

The following is 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

To create an HTTP request, you can use the open () method of the xmlhttpreques t object. Its syntax code is as follows:

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

Parameter resolution:

  • methodHTTP methods to be used, such as “get”, “post”, “put”, “delete”, etc.
  • urlRepresents the URL address to which to send the request.
  • Async (optional)An optional Boolean parameter that indicates whether to execute the operation asynchronously. The default value is true. If the value is false, the send () method will not return until a reply is received. If true, notifications of completed transactions are available to event listeners. If the multipart property is true, this must be true, otherwise an exception will be thrown.
  • User (optional)The user name used for authentication purposes. The default value is null.
  • Password (optional)Password for authentication purposes. The default value is null.

3. Set the function to respond to the change of HTTP request status and the function to return information from the server

After creating the HTTP request, you should be able to send the HTTP request to the web server. However, the purpose of sending an HTTP request is to receive data returned from the server. From the creation of XMLHttpRequest object to sending data, receiving data and XMLHttpRequest object, the following five states will be experienced:

  • Uninitialized state. When the XMLHttpRequest object is created, the object is in an uninitialized state. At this time, the readyState property value of the XMLHttpRequest object is 0.
  • Initialization status. After creating the XMLHttpRequest object, when the HTTP request is created using the open () method, the object is in an initialized state. At this time, the readyState property value of the XMLHttpRequest object is 1.
  • Send data status. After initializing the XMLHttpRequest object, when sending data using the send () method, the object is in the send data state. At this time, the readyState property value of the XMLHttpRequest object is 2.
  • Receive data status. After receiving and processing the data, the web server transmits the returned results to the client. At this time, the XMLHttpRequest object is in the received data state, and the readyState property value of the XMLHttpRequest object is 3.
  • Completion status. After receiving data, the XMLHttpRequest object enters the completion state. At this time, the readyState property value of the XMLHttpRequest object is 4. At this time, the received data is stored in the memory of the client computer. You can use the responseText property or responsexml property to obtain the data.

In general, the readyState property has the following values:

  • 0 (uninitialized) or(The request has not been initialized)
  • 1 (loading) or(EstablishedServer (link)
  • 2 (loaded successfully) or(Request accepted)
  • 3 (Interactive) or(Processing request)
  • 4 (completed) or(The request is complete and the response is ready)

The read-only property xmlhttprequest.status returns the numeric status code in the XMLHttpRequest response. The value of status is aunsigned short 。 Before the request is completed, the value of status is 0. It is worth noting that if XMLHttpRequest fails, the status returned by the browser is also 0:

  • Unsent (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);

Only after the XMLHttpRequest object completes the above five steps can it obtain the data returned from the server. Therefore, if you want to obtain 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
    }
}

4. Send HTTP request

XMLHttpRequest.send(data);

end

Finally, attach a simple and complete Ajax example:

<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>

Ajax introduction and use of front-end JS

~

~

~End of this article

~

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

hello everyone! I am the author of programming SamadhiRecluse KingMy official account is “programming samadhi”. Welcome to pay attention to it. I hope you can give us more advice.

Pay equal attention to knowledge and skills, cultivate both internal and external skills, grasp both theory and practice, and be hard on both hands!

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]