This is my 13th day of the Genwen Challenge

I. Introduction to Ajax:

  1. AJAX technology makes it possible to update parts of a web page without reloading the entire page. AJAX is widely used in WEB applications. It can be seen everywhere in common PC WEB pages and various WEB apps of Baidu, Taobao, jingdong and so on. AJAX has become one of the permanent skills of front-end engineers.
  2. AJAX, of course, is not a programming language, but a way of putting existing standards together.

2. Introduction to JSON

  1. Today, Ajax applications generally use JSON format.
  2. JSON(JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript (the JS specification of the European Computer Association) and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clarity of the hierarchy make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation, and effectively improve the efficiency of network transmission.

Iii. Advantages and disadvantages of Ajax:

Advantages:

  1. You can communicate with the server without refreshing the page.
  2. Allows partial page content to be updated based on user events.

Disadvantages:

  1. No browsing history, no fallback to speak of.
  2. Cross-domain problems exist.
  3. Not SEO friendly.

Introduction to the HTTP protocol

  1. Hypertext Transfer Protocol (HTTP) is a simple request-response Protocol that usually runs on top of TCP.
  2. The communication rules between the browser and the world Wide Web server are specified in detail.
  3. The format is as follows.

Request packet (including four parts) : 1. Line request + / path + protocol version 2. Header name: Value 3. Empty line 4. Empty for GET request, not empty for POST request.

Response packet (consisting of four parts) : 1. Line protocol version + response status code + response status string for example, HTTP/1.1 200 OK 2. Header name: value 3. blank line 4. body Returns HTML content

Five: AJAX use:

1. Basic request operations

Let the name = XHR;

  // 1. Create objects
     constName =new XMLHttpRequest();
     // let the name = XHR;
     // 2. Initialize the request method and url request address
     xhr.open('GET'.'http://............ ');
     / / 3. Send
     xhr.send();
      // 4. Event binding, handling the server return result
     xhr.onreadystatechange = function(){
         // Check that the server returns all results
         if(xhr.readyState === 4) {// Check the response status code 200 404 403 500.... Etc.
             // 2xx indicates success
             if(xhr.status>=200&&xhr.status<300) {// The result is processed here;
                // console.log(xhr.status); Get the status code
               // console.log(xhr.statusText); The status string is available
               // console.log(xhr.getAllResponseHeaders()); All response headers are available
               // console.log(xhr.response); The response body is obtained. The obtained data is processed here.... A little... }else{}}}Copy the code
Set request parameters:

After the address? + parameter = value. Multiple parameters are separated by ampersand

 xhr.open('GET'.'http://............ ? a=50&b=10');
Copy the code
3. Ajax POST request and set request parameters:
 xhr.open('POST'.'http://............ ');
Copy the code

Send () can be set to any format, such as:

xhr.send('a=100&b=200&c=250');
Copy the code
xhr.send('a:100&b:200&c:250');
Copy the code
xhr.send('123456789');
Copy the code

.

3. Ajax set request header information:

I’ll write it under open (). Predefined or custom names can be written. The back end will give. Xhr.setrequestheader (‘ name ‘, ‘value’);

. Slightly XHR. Open ('GET'.'http://............ '); Xhr.setrequestheader (' name ', 'atguigu'); xhr.send(); . slightlyCopy the code
4. Response to JOSN data:

(1) Manually convert to JSON data: write in the processing result.

let data = JSON.parse(xhr.response);
Copy the code

(2) Automatic conversion (recommended) : write in xhr.open().

xhr.responseType = 'JSON';
Copy the code
5. Solve the old IE cache problem:
xhr.open("GET".'http://...... ? t='+ Data.now());
Copy the code
6. Network request timeout and exception handling:
. slightlyconst xhr = new XMLHttpRequest();
 // Set 2s to timeout
 xhr.timeout = 2000;
 // After the timeout callback, you can set some beautiful reminder effect
 xhr.ontimeout = function(){
       alert("Please try again later!");
 }
 // Network exception callback
 xhr.onerror = function(){
       alert("There seems to be a problem with the network!); }... slightlyCopy the code
7. Repeat request sending problem:

Sometimes the load is slow, and users are eager to send the same request, which causes a heavy load on the server. Problem: Processing: The last incomplete request is cleared, resend, keep only one request.

let x=null;
// Define a variable to determine whether a request is being sent
let isSending = false; .// In the event to send the request (if the request is to be sent, do the following) :{...if(isSending) x=abort(); // Cancel the request and send a new one
x = new XMLHttpRequest();
isSending = true; // The request is being sent.// If all results are returned, complete the request
   if(xhr.readyState === 4){
        isSending = false; }... }Copy the code
8. Axios sends simple Ajax requests:

Axios GET request:

axios.get('http://... ', {// Set url parameters, such as:
   params: {
     id: 50.vip: 5
  }    
  // Set the request header parameters, such as:
  headers: {
     name: 'night'.age: 21
  }
}).then(value= > {
  // Process the result
     console.log(value); })Copy the code

POST request:

axios.post('HTTP:... ', {
/ / request body
    username: 'admin'.password: 'admin'}, {// Set url parameters, such as:
    params: {
     id: 50.vip: 5
      },
      // Set the request header parameters, such as:
     headers: {
     width: 150.height: 200,}});Copy the code
9. Sending ajax requests as axios functions (this is much clearer and intuitive) :
axios({
      // Request the address url
   url: 'https.... '.// Request methods, such as:
   method: 'POST'.// Request parameters such as:
   params: {
      id: 5
   }
     // Request header information, such as:
   headers: {
      a: 100.b: 200
   }
    // Request body information:
   data: {
    username: 'admin'.password: 'admin'
   }
}).then(response= > {
  // This handles the return result
     // Response status code
     console.log(response.status);
     // Response status string
     console.log(response.statusText);
     // Response header information
     console.log(response.headers);
     // The response body is the main part of the data obtained
     console.log(response.data);
})
Copy the code
10. Use the Fetch function to send ajax requests:

The Fetch API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to fetch resources asynchronously across a network. The Fetch document

fetch('https://..... ', {// Request methods, such as:
  method: 'POST'.// Request headers, such as:
  headers: {
    name: 'night'
  },
// Request body, such as:
  body: 'username=admin&password=admin'
}).then(response= > {
  // Convert to JSON format
  return response.json();
}).then(response= > {
  // Process the result data
  console.log(response);
})
Copy the code
11…. Slightly, continue to improve the update…..