[Web front-end] Ajax super detailed explanation

1. Introduction to AJAX

AJAX: The full name isAsynchronous JavaScript And XML, which is asynchronous JavaScript and XML. AJAX is a tool for front-end and back-end interaction, which means that through AJAX as a bridge, the client can send messages to the server and receive response messages from the server.

Two ways to implement AJAX:

  • XHR:Use XMLHttpRequest object to implement AJAX
  • Fetch: Use Fetch API to implement AJAX

XHR sum Fetch distinction:

function points XHR Fetch
Basic request capabilities
Basic access to responsiveness
Monitor request progress
Monitor response progress
Is it available in Service Worker
Controlling the carrying of cookies
Control redirection
Request cancellation
Custom referrer
flow
API style Event Promise
Activity Stop updating constantly updated

2. Front-end and back-end interaction

Since AJAX is a tool for front-end and back-end interaction, in order to have a more convenient and in-depth understanding of AJAX and its subsequent implementation, it is necessary to supplement the relevant knowledge of front-end and back-end interaction.

The protocol used for front-end and back-end interaction is the HTTP protocol, which stipulates two aspects:

  • Message delivery pattern
  • The format of the message

1. The mode of transmitting messages is the "request-response" mode

  • The one who initiates the request is called the client, and the one who receives the request and completes the response is called the server.
  • After the "request-response" is completed, an interaction ends.

Insert image description here

2. The format of the message is plain text, divided into the following three parts:

请求行
请求头

请求体

Insert image description here

3. XHR

In order to save the cost of learning, this article focuses on explaining the front-end content. For the back-end part, simulated data and existing tools are used to complete the implementation of the back-end.

Use the following three methods to simulate the backend and develop Ajax from shallow to deep:

  • Use JSON files to simulate data returned by the backend
  • Call the network interface to obtain the data returned by the backend
  • Use json-server to simulate the server to implement various request methods

3.1 XMLHttpRequest object

1.XMLHttpRequest Methods of objects

method describe
abort() Abort current request
getAllResponseHeaders() Return all response headers
getResponseHeader() Return specific response headers
open() Specify how to request
send() Send request to server
setRequestHeader() Set request header

2.XMLHttpRequest Illustrative attribute

Attributes describe
onreadystatechange Define the function that is called when the readyState property changes
readyState Save the state of XMLHttpRequest
responseText Return response data as a string
responseXML Return response data as XML data
status Returns the status number of the request
statusText Return status text

3.2 Obtain simulated backend data

Nowadays, text data in front-end and back-end interaction is commonly used in json format, so json files are used here to simulate the data returned by the back-end.

Create a new onetest.json in the same directory of the current page to simulate the data returned by the backend. The content is as follows

{
    
    
  "name": "Bill",
  "age": 18
}

1. Send a request to the server

open(method, url, async): Initialize a newly created request, or reinitialize a request

  • method: Request method, such as GET, POST, etc.
  • url:The location of the server file
  • async: Whether to perform the operation asynchronously, async is true
var xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true); // 创建请求,以GET请求的方式,请求服务器的test.json
xhr.send(); // 发送请求

PressF12, then refresh the page, click Network, then select Fetch/XHR, you can see that there is one a>test.jsonFile

Insert image description here

Double-clicktest.json and then select Response. You can see that the response data content is the content in test.json a>

Insert image description here

2. Based on the status of XMLHttpRequest and HTTP, determine whether the request is successful and obtain the response data

  • onreadystatechange: Define the function that is called when the readyState property changes (triggers the readystatechange event)
  • readyState:The status of XMLHttpRequest
    • 0:The request is not initialized
    • 1: Server connection established
    • 2: Request received
    • 3: Processing request
    • 4: The request is complete and the response is ready
  • status: HTTP status code, 200-299 indicates that the request is successful. For the specific status code meaning, please refer to Common HTTP Status code summary
    • 200:OK
    • 403:Forbidden
    • 404:Not Found
  • responseText: Response data returned in string form

Note: From the above, it can be concluded that when readyState === 4 and status are in the range of [200,300), it means this request Complete normally.

var xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true);
xhr.send();

// readyState属性发生变化时调用的函数
xhr.onreadystatechange = function () {
    
    
  if (xhr.readyState === 4) {
    
     // 请求已完成且响应已就绪
    if (xhr.status === 200) {
    
     // 请求成功
      console.log(JSON.parse(xhr.responseText)); // 打印服务器的响应文本
    } else {
    
    
      console.log(xhr.status, xhr.statusText); // 打印响应状态码和响应状态文本
      console.log(xhr.responseText);
    }
  }
};

Refresh the page and the results are as follows:

Insert image description here

By modifying test.json in the above code to test1.json, a file that does not exist in the request server is constructed. The running results are as follows:

Insert image description here

3. You can use the onload attribute instead of onreadystatechange and readyState === 4

Note: The onload attribute indicates that the load event will be triggered when an XMLHttpRequest request is completed.

var xhr = new XMLHttpRequest();
xhr.open("GET", "test.json", true);
xhr.send();

// XMLHttpRequest请求完成的时候会触发load事件
xhr.onload = function () {
    
    
  // 使用正则表达式,判断xhr.status范围是否在[200,300)
  if (/^2\d{2}$/.test(xhr.status)) {
    
    
    console.log(JSON.parse(xhr.responseText));
  } else {
    
    
    console.log(xhr.status, xhr.statusText);
    console.log(xhr.responseText);
  }
};

3.3 Obtain network data

Call the network interface to change the simulated data to the real data of the network.

Changetest.json in the above code to the following network address:

http://www.xiongmaoyouxuan.com/api/tabs

1. Request to the network server

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.xiongmaoyouxuan.com/api/tabs", true); 
xhr.send();

// XMLHttpRequest请求完成的时候会触发load事件
xhr.onload = function () {
    
    
  if (/^2\d{2}$/.test(xhr.status)) {
    
    
    console.log(JSON.parse(xhr.responseText));
  } else {
    
    
    console.log(xhr.status, xhr.statusText);
    console.log(xhr.responseText);
  }
};

The running results are as follows:

Insert image description here

Since the json data is too long, part of the data is posted here for reference:

{
    
    
  "code": 200,
  "data": {
    
    
    "list": [
      {
    
    
        "commoditiesBoardId": 0,
        "id": 1,
        "name": "今日推荐",
        "imageUrl": "http://img1.lukou.com/static/p/fb/tab/1/20181211-151644.jpeg",
        "extraData": "{\"need_banner\": 1, \"category_id\": 13, \"need_grid\": 1}",
        "flowBoardId": 89,
        "note": "小编精选,全场特惠 (ง •̀_•́)ง",
        "gridsBoardId": 3,
        "bannerBoardId": 2,
        "feedsBoardId": 0,
        "categoryId": 0
      },
      {
    
    
        "commoditiesBoardId": 157,
        "id": 2,
        "name": "女装",
        "imageUrl": "http://img1.lukou.com/static/p/fb/tab/2/20190220-155007.png",
        "extraData": "{\"category_id\": 1, \"fe_category_id\": 1689}",
        "flowBoardId": 75,
        "note": "",
        "gridsBoardId": 4,
        "bannerBoardId": 0,
        "feedsBoardId": 5,
        "categoryId": 1689
      }
    ]
  }
}

2. Process the data returned by the server and render it on the page

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>点击查询商品</button>
    <ul>
      <li>
        <p>今日推荐</p>
        <img src="http://img1.lukou.com/static/p/fb/tab/1/20181211-151644.jpeg" />
      </li>
    </ul>
    <script>
      var btn = document.querySelector("button");
      var ul = document.querySelector("ul");

      // 注册点击事件
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://www.xiongmaoyouxuan.com/api/tabs", true);
        xhr.send();

        // XMLHttpRequest请求完成的时候会触发load事件
        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            var responseData = JSON.parse(xhr.responseText); // 响应数据
            console.log(responseData);
            render(responseData); // 渲染数据
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };

      // 处理获取的响应数据,并将其渲染到页面上
      function render(responseData) {
      
      
        var commodityList = responseData.data.list.map(function (commodity) {
      
      
          return `<li>
            <p>${ 
        commodity.name}</p>
            <img src="${ 
        commodity.imageUrl}" />
          </li>`;
        });
        console.log(commodityList);
        ul.innerHTML = commodityList.join("");
      }
    </script>
  </body>
</html>

Click the button and the results are as follows:

Insert image description here

3.4 Use json-server to simulate the server

json-server can simulate a server: download node.js, install json-server, create a new json file, and run the json file through json-server. At this time, the json file has basic back-end server capabilities. Can complete some basic additions, deletions, modifications and checks.

3.4.1 Install node.js

1. Download and installnode.js, enter thenode official website, select theLTS version and click to download the installation package

node official location:https://nodejs.org/en

Insert image description here

2. Double-click the installation package and keep clicking Next to complete the installation.

Insert image description here

3. Open cmd, enter node -v and npm -v, if the version number appears, the installation is successful

Insert image description here

4. Switch the mirror source to the domestic Taobao mirror source to improvenpmdownload speed

# 设置镜像源
npm config set registry https://registry.npm.taobao.org 
# 查看镜像源
npm config get registry 

Insert image description here

3.4.2 Install and use json-server

1. Enter the following command to install json-server

npm install -g json-server

Insert image description here

2. After installing json-server, create a new filetest.json with the following content

{
    
    
  "users": [
    {
    
    
      "id": 1,
      "name": "Bill"
    },
    {
    
    
      "id": 2,
      "name": "Jackson"
    }
  ],
  "shopcar": ["女装", "男装", "配饰", "零食", "母婴用品", "箱包"]
}

3. Open cmd, switch the path to the path where test.json is located, enter the command json-server test.jsonRun the server, and get the server address as follows

http://localhost:3000/users
http://localhost:3000/shopcar

Insert image description here

4. Current pageindex.html, enter the following content

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/users", true); // 向json-server服务器发送请求
xhr.send();

xhr.onload = function () {
    
    
  if (/^2\d{2}$/.test(xhr.status)) {
    
    
    console.log(JSON.parse(xhr.responseText));
  } else {
    
    
    console.log(xhr.status, xhr.statusText);
    console.log(xhr.responseText);
  }
};

5. Since json-server will conflict with Live Server, you cannot use Live Server to open the browser. You can download the plug-in< /span>Preview on Web Server, use this plug-in to open the browser.

Right-clickvscode-preview-server:Launch on browser to open the page.

Insert image description here

Open the console and the running results are as follows, indicating that the data returned by the server has been obtained:

Insert image description here

3.5 Common request methods

Request method describe
GET retrieve data
POST submit data
PUT Update all data
PATCH Update some data
DELETE delete data
HEAD Get server header information
OPTIONS Get server device information
CONNECT Reserve request method

Use to simulate the server in section 3.4 to simulate the following 5 common request methods. json-server

test.jsonThe content of is the content in the section 3.4.2. In the path where test.json is located, enter the following command to start json-server:

json-server test.json --watch

3.5.1 GET request

GETRequest: used to obtain data from the server.

GETThere are two ways to request:

  • Without parametersGETRequest to obtain all data of the server address
  • Request with parametersGET to obtain specific data of the server address

1. Request without parametersGET to obtain all data from the server

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>GET</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://localhost:3000/users", true); // 创建一个GET请求
        xhr.send();

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText));
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Right-clickvscode-preview-server:Launch on browser, open the page and click the GET button. The results are as follows:

Insert image description here

2. Request with parametersGET to obtain specific data of the server address

If you need to obtain specific data, just add data in the format ofkey=value to the original address.

  • key=value: Get a single specific data
  • key=value&key=value: Get multiple specific data

key=value: For example, requesting the server to obtain the data of id=1 can modify http://localhost:3000/users to http://localhost:3000/users?id=1. The running result is as follows: < /span>

Insert image description here
key=value&key=value: For example, request the server to obtain the data of id=1 and id=2, you can modify http://localhost:3000/users to < a i=4>, the running results are as follows:http://localhost:3000/users?id=1&id=2

Insert image description here

3.5.2 POST request

POSTRequest: used to submit data to the server.

POSTThere are two formats for submitting text data:

  • form format: that is, a string in the format of key=value, set content-type to application/x-www-form-urlencoded
  • json format: that is, a string in the format of json, set content-type to application/json

1. Useform encoding format string to submit data to the server

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>POST</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:3000/users", true); // 创建一个POST请求
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); // 设置请求头的content-type属性值为form编码
        data = "name=Michael&age=18"; // form编码格式的数据
        xhr.send(data); // 发送数据

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText)); 
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Open the page and click the POST button. After the operation is completed, it is found thattest.jsonthe file has added the data just submitted

Insert image description here

2. Use strings in the format ofjson to submit data to the server

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>POST</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:3000/users", true); // 创建一个POST请求
        xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
        data = JSON.stringify({
      
       name: "Ada", age: 18 }); // json格式的字符串
        xhr.send(data); // 发送数据

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText));
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Open the page and click the POST button. After the operation is completed, it is found thattest.jsonthe file has added the data just submitted

Insert image description here

3.5.3 PUT request

PUTRequest: used to update the server's data, update the data in an overlay manner, that is, update all the data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>PUT</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("PUT", "http://localhost:3000/users/4", true); // 创建一个PUT请求,请求更新id为4的数据
        xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
        data = JSON.stringify({
      
       age: 28 }); // 更新age
        xhr.send(data); // 发送数据

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText));
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Note: The updated path must be specified accurately. http://localhost:3000/users/4 in /4 represents the data with id 4

Open the page and click the PUT button. After running, it is found thattest.json file has updated the age data just sent, and it is an overwriting update. The previous name attribute data has been overwritten. .

Insert image description here

3.5.4 PATCH request

PATCHRequest: used to update server data, update data in a patch manner, that is, update part of the data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>PATCH</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("PATCH", "http://localhost:3000/users/3", true); // 创建一个PATCH请求,请求更新id为3的数据
        xhr.setRequestHeader("content-type", "application/json"); // 设置请求头的content-type属性值为json格式
        data = JSON.stringify({
      
       age: 28 }); // 更新age
        xhr.send(data); // 发送数据

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText));
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Open the page and click the PATCH button. After running, it is found thattest.json file has updated the age data just sent, and it is a patch update. The previous name attribute data will not be overwritten. , remains the same.

Insert image description here

3.5.5 DELETE request

DELETERequest: used to delete data from the server.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>DELETE</button>
    <script>
      var btn = document.querySelector("button");
      btn.onclick = function () {
      
      
        var xhr = new XMLHttpRequest();
        xhr.open("DELETE", "http://localhost:3000/users/4", true); // 创建一个DELETE请求,请求删除id为4的数据
        xhr.send(); // 发送请求

        xhr.onload = function () {
      
      
          if (/^2\d{2}$/.test(xhr.status)) {
      
      
            console.log(JSON.parse(xhr.responseText));
          } else {
      
      
            console.log(xhr.status, xhr.statusText);
            console.log(xhr.responseText);
          }
        };
      };
    </script>
  </body>
</html>

Open the page and click the DELETE button. After the operation is completed, it is found that the data with ID 4 in the filetest.json has been deleted.

Insert image description here

4. Fetch

Note: Essential learningFetch, demand learningES6intermediatePromisemoreasyncawait.

UsingFetch for front-end and back-end interaction is to initiate a request to obtain resources through the fetch() method, which returns a promise , this promise will be resolve after the request response, and the Response object will be returned.

4.1 Fetch API

The Fetch API includes the following parts:

  • HeadersInterface: Information that represents request headers or response headers, allowing various operations to be performed on HTTP request and response headers.
  • RequestInterface: represents resource request
  • ResponseInterface: Represents the response data of the request
  • fetch()Method: used to initiate a request to obtain resources

HeadersObject methods:

method describe
Headers.append() Add a value to an existing header
Headers.set() Replace existing header value
Headers.get() Get all values ​​of the specified header
Headers.delete() Delete the specified header

RequestObject properties:

Attributes describe
Request.method Request method
Request.url Requested URL
Request.headers Request related Headers objects
Request.credentials Requested certificate
Request.mode requested mode
Request.cache Requested cache mode

ResponseObject properties:

Attributes describe
Response.headers Headers object associated with Response
Response.status Response status code
Response.statusText Status information consistent with the Response status code
Response.url Response URL

ResponseObject instance methods:

method describe
Response.json() Parse response body into json object
Response.text() Parse response body into string
Response.formData() Parse the response body into a fromData form object
Response.blob() Parse response body into binary blob object
Response.arrayBuffer() Parse the response body into a binary arrayBuffer object

fetch()method:

Promise<Response> fetch(input[, init]);

  • input: Defines the resource to be obtained, this could be:
    • A string containing the URL of the resource to be retrieved
    • a request object
  • init: A configuration item object, including all settings for the request. Optional parameters are:
    • method: Request method
    • headers: Request header information
    • body: Request body information
    • mode: Requested mode
    • credentials:requested certificate
    • cache: Requested cache mode
    • redirect: How to handle redirection patterns

4.2 Use Fetch to complete the request

Still using json-server to simulate the server, simulate GET, POST, PUT, PATCH, and DELETE, these five common request methods.

test.jsonThe content of is the content in the section 3.4.2. In the path where test.json is located, open cmd and enter the following command to start json-server

json-server test.json --watch

Insert image description here

4.2.1 GET request

Since the request is asynchronous, async and await are used here.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>GET</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        const resp = await fetch("http://localhost:3000/users"); // 等待拿到响应头,拿到响应头promise就完成了
        const data = await resp.json(); // 等待解析响应体,使用json格式解析响应体
        console.log(resp); // 响应头
        console.log(data); // 响应体
      };
    </script>
  </body>
</html>

Right-clickvscode-preview-server:Launch on browser, open the page and click the GET button. The results are as follows:

Insert image description here

The following two lines of code can be reduced to one line:

const resp = await fetch("http://localhost:3000/users"); // 等待拿到响应头,拿到响应头promise就完成了
const data = await resp.json(); // 等待解析响应体,使用json格式解析响应体

After simplification:

const data = await fetch("http://localhost:3000/users").then(resp => resp.json());

4.2.2 POST request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>POST</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        // 请求的信息
        init = {
      
      
          method: "POST",
          headers: {
      
       "content-type": "application/json" },
          body: JSON.stringify({
      
       name: "Ada", age: 18 })
        };

        // 发送请求
        const data = await fetch("http://localhost:3000/users", init).then(resp => resp.json());
        console.log(data);
      };
    </script>
  </body>
</html>

Open the page and click the POST button. The results are as follows:

Insert image description here

4.2.3 PUT request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>PUT</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        // 请求的信息
        init = {
      
      
          method: "PUT",
          headers: {
      
       "content-type": "application/json" },
          body: JSON.stringify({
      
       age: 28 })
        };

        // 发送请求
        const data = await fetch("http://localhost:3000/users/3", init).then(resp => resp.json());
        console.log(data);
      };
    </script>
  </body>
</html>

Open the page and click the PUT button. The results are as follows:

Insert image description here

4.2.4 PATCH request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>PATCH</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        // 请求的信息
        init = {
      
      
          method: "PATCH",
          headers: {
      
       "content-type": "application/json" },
          body: JSON.stringify({
      
       age: 28 })
        };

        // 发送请求
        const data = await fetch("http://localhost:3000/users/2", init).then(resp => resp.json());
        console.log(data);
      };
    </script>
  </body>
</html>

Open the page and click the PATCH button. The results are as follows:

Insert image description here

4.2.5 DELETE request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>DELETE</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        // 请求的信息
        init = {
      
       method: "DELETE" };

        // 发送请求
        const data = await fetch("http://localhost:3000/users/3", init).then(resp => resp.json());
        console.log(data);
      };
    </script>
  </body>
</html>

Open the page and click the DELETE button. The results are as follows:

Insert image description here

5. Axios

Axios: It is a third-party HTTP library based on promise encapsulation, which can be used in browsers and node.js.

5.1 Axios API

Axios location: https://www.npmjs.com/package/axios

Open the Axios website and you will see a directory that contains Axios installation tutorials, API usage tutorials, examples, etc.

Insert image description here

1. Installation: There are many installation methods. Here we introduce the axios library by referencing external js files.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>

2.API usage method

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

The config configuration can refer to the following:

// Send a POST request
axios({
    
    
  method: 'post',
  url: '/user/12345',
  data: {
    
    
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

5.2 Use Axios to complete the request

Still using json-server to simulate the server, simulate GET, POST, PUT, PATCH, and DELETE, these five common request methods.

test.jsonThe content of is the content in the section 3.4.2. In the path where test.json is located, open cmd and enter the following command to start json-server

json-server test.json --watch

1.GET request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入axios库 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
  </head>
  <body>
    <button>GET</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        await axios
          .get("http://localhost:3000/users") // 发送GET请求
          .then(res => {
      
      
            console.log(res); // 响应的全部内容
            console.log(res.data); // 响应的数据内容
          })
          .catch(err => {
      
      
            console.log(err);
          });
      };
    </script>
  </body>
</html>

Right-clickvscode-preview-server:Launch on browser, open the page and click the GET button. The results are as follows:

Insert image description here
If you want to send a GET request with parameters, you can modify axios.get() to the following content:

// 获取id=1的数据
axios.get("http://localhost:3000/users", {
    
    
  params: {
    
    
    id: 1 
  }
});

2.POST request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入axios库 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
  </head>
  <body>
    <button>POST</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        await axios
          .post("http://localhost:3000/users", {
      
       name: "Ada", age: 18 }) // 发送POST请求
          .then(res => {
      
      
            console.log(res.data);
          })
          .catch(err => {
      
      
            console.log(err);
          });
      };
    </script>
  </body>
</html>

If you want to use the form encoding format, you can modifyaxios.post() to the following content:

axios.post("http://localhost:3000/users", "name=Michael&age=18")

3.PUT request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入axios库 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
  </head>
  <body>
    <button>PUT</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        await axios
          .put("http://localhost:3000/users/3", {
      
       age: 28 }) // 发送PUT请求
          .then(res => {
      
      
            console.log(res.data);
          })
          .catch(err => {
      
      
            console.log(err);
          });
      };
    </script>
  </body>
</html>

4.PATCH request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入axios库 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
  </head>
  <body>
    <button>PATCH</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        await axios
          .patch("http://localhost:3000/users/2", {
      
       age: 28 }) // 发送PATCH请求
          .then(res => {
      
      
            console.log(res.data);
          })
          .catch(err => {
      
      
            console.log(err);
          });
      };
    </script>
  </body>
</html>

5.DELETE request

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入axios库 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
  </head>
  <body>
    <button>DELETE</button>
    <script>
      const btn = document.querySelector("button");
      btn.onclick = async function () {
      
      
        await axios
          .delete("http://localhost:3000/users/3") // 发送DELETE请求
          .then(res => {
      
      
            console.log(res.data);
          })
          .catch(err => {
      
      
            console.log(err);
          });
      };
    </script>
  </body>
</html>

Guess you like

Origin blog.csdn.net/aidijava/article/details/129504429