preface

This is my second article on getting started, documenting the basics of ajax for later review.

  • Ajax based
  • Promise + Ajax memo

First, Ajax basics

Document link rookie/document link MDN

AJAX profile

AJAX is Asynchronous JavaScript And XML. Simply put, you use the XMLHttpRequest object to communicate with the server. It can send and receive data using JSON, XML, HTML, and TEXT text formats. The most attractive aspect of AJAX is its “asynchronous” nature, meaning that it can communicate with the server, exchange data, or update the page without having to refresh the page.

Step 1 – How to send AN HTTP request

The process can be roughly divided into three steps:

  1. Send an HTTP request.
  2. When the response is received, XMLHttp is told which JS function handles the response in the request object and is called when the state of the request changes.
  3. Send an actual request by calling the open() and send() methods of the HTTP request object.
  (function(){
      // Create an XMLHttpRequest object to exchange data with the server in the background (1. Send an HTTP request)
      var httpRequest;

      // To handle all modern browsers, including IE5 and IE6, check whether the browser supports the XMLHttpRequest object
      if(window.XMLHttpRequest){
        // Execute code for Internet Explorer 7+, Firefox, Chrome, Opera, Safari
        httpRequest = new XMLHttpRequest();
      }else{
        // IE6, IE5 executes code
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
      
      // When you use async=false, do not write the onreadyStatechange function. Just change the third argument in the open() method to false.
      // When async=true, specify the function to execute when the response is in the readystate in the onReadyStatechange event
      // 2. After sending a request, you will receive a response. At this stage, you tell the XMLHttp request object which JavaScript function handles the response, give it a name after setting the object's onreadyStatechange property, and call the function when the request state changes.
      httpRequest.onreadystatechange = function(){
        if(httpRequest.readyState === 4) {if(httpRequest.status === 200) {console.log("Request successful",httpRequest.responseText);
          }else{
            console.log("An error occurred.",httpRequest.status); }}}// 3. Next, declare what you will do when you receive a response. You will send an actual request by calling the open() and send() methods of the HTTP request object, as follows:

      // Specifies the type of request, the URL, and whether to process the request asynchronously.
      / / GET demonstration
      // httpRequest.open("GET","/try/ajax/demo_get2.php? fname=Henry&lname=Ford",true);
      // httpRequest.send(); 

      / / POST presentation
      httpRequest.open("POST"."/try/ajax/demo_post2.php".true);
      httpRequest.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); // If you are using POST data, you need to set the MIME type of the request.
      httpRequest.send("fname=Henry&lname=Ford"); }) ();Copy the code

Step 2 – Process the server response

When you send a request, the JavaScript function you provide is responsible for handling the response. What should this function do?

  • First, the function checks the state of the request (Httprequest.readyState === 4).
  • Next, check the HTTP response code (httprequest.status === 200).

After checking the status of the request and the HTTP response code, you can do whatever you want with the data returned from the server. There are two ways to access this data:

  • Httprequest. responseText – Returned by the server as text characters
  • Httprequest.responsexml – returns it as an XMLDocument object, which you can then process using JavaScript

Note that this step only works if you make an asynchronous request (i.e. the third argument to open() is not specified or set to true). You don’t need to use the function if you are making a synchronous request, but doing so is highly frowned upon as it gives a poor user experience.

The onreadystatechange event

When the request is sent to the server, we need to perform some response-based tasks. Each time readyState changes, the OnReadyStatechange event is triggered. The readyState property holds the state information for the XMLHttpRequest.

Here are the three important properties of the XMLHttpRequest object:

  1. onreadystatechange

    • Stores the function (or function name) that is called whenever the readyState property changes.
  2. ReadyState – Holds the state of the XMLHttpRequest. It goes from 0 to 4.

    • 0: (uninitialized) or (request not initialized)
    • 1: (loading) or (established server link)
    • 2: (load successfully) or (request accepted)
    • 3: (interaction) or (processing request)
    • 4: (completed) or (request completed and response ready)
  3. status

    • 200: “OK”
    • 404: Page not found

In the onreadyStatechange event, specify the task to perform when the server responds that it is ready to be processed. When readyState is equal to 4 and the state is 200, a response is ready.

Promise + Ajax memo

Reference links/documentation links

Introduction of Promise

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations.

The Promise constructor takes only one argument and is a function that is run asynchronously directly after construction, so we call it the starting function. The start function takes two arguments, resolve and reject.

When a Promise is constructed, the starting function is executed asynchronously:

new Promise(function (resolve, reject) {
    console.log("Run");
});
// Output Run directly
Copy the code

Resolve and reject are both functions, where a call to resolve indicates that everything is fine, and reject is called when an exception occurs

The Promise class has.then().catch() and.finally() methods, each of which takes a single function.

  • .then() adds the function in the argument to the normal execution sequence of the current Promise.
  • .catch() is the exception handling sequence that sets the Promise.
  • .finally() is the sequence that must be executed at the end of the Promise execution.

The functions passed in.then() are executed sequentially, with any exceptions jumping directly to the catch sequence.

Resolve () can place an argument to pass a value to the next THEN, and a function in the THEN can return a value to pass to the THEN. However, if the then returns a Promise object, the next THEN will act on the returned Promise.

The reject() argument typically passes an exception to a subsequent catch function that handles the exception.

Please note the following two points:

  • Resolve and Reject are scoped only to start functions and do not include THEN and other sequences.
  • Resolve and reject do not stop the start function. Don’t forget to return.

Use case

Source of case

  const getJSON = function(url){
    const promise = new Promise(function(resolve,reject){

      const handler = function(){
        if(this.readyState ! = =4) {return;
        }
        if(this.status === 200){
          resolve(this.response)
        }else{
          reject(new Error(this.statusText))
        }
      };

      const xmlHttp = new XMLHttpRequest();

      xmlHttp.open("GET",url);
      xmlHttp.onreadystatechange = handler;
      xmlHttp.responseType = "json";
      xmlHttp.setRequestHeader("Accept"."application/json");
      xmlHttp.send();

    });

    return promise;
  };


  getJSON("/test.json").then(function(json){
    console.log("Request successful",json)
  },function(error){
    console.log("An error occurred.",error)
  });
Copy the code

conclusion

The ajax basics themselves are not difficult, but you may not be able to remember the specific parameters and processes because there are so many good plug-ins.

I’ve always thought the basic knowledge is king, go up step by step, also want to take strong steps, but the memory also is not very good, learned, must be will forget, so records and sharing is a good habit, hope you can consider, learn new technology, also don’t forget the underlying technology.

One more step away from the pillow. Come on, go!