How the front end sends requests

1. Form submission

In order to demonstrate the following case, we first use node.js to write a simple server to receive requests sent by the front end.

//引用模块
const express = require('express');
创建对象
var app = express();

// post请求的两种解析方式
app.use(express.json());
app.use(express.urlencoded({
    
    extended:true}))
// 设置静态目录
app.use(express.static(__dirname+"/public"))
//get请求   定义了接口/login
app.get("/login",(req,res)=>{
    
    
    console.log();
    res.json({
    
    
        code:1000,
        msg:"get-成功",
        name:req.query.name,
        psw:req.query.psw
    })
})
//post请求
app.post("/register",(req,res)=>{
    
    
    console.log();
    res.json({
    
    
        code:1000,
        msg:"post-成功",
        name:req.body.name,
        psw:req.body.psw
    })
})
//监听服务端口
app.listen(8089,()=>{
    
    
    console.log("8089服务启动");
})

The following is a case of submitting data in a form

<form action="/login" method="get">
      <input type="text" name="name">
      <input type="text" name="psw">
      <input type="submit" value="get">
</form>
<form action="/register" method="post">
      <input type="text" name="name">
      <input type="text" name="psw">
      <input type="submit" value="post">
</form>

The from form submits all the content in the form to the background, such as input boxes, radio buttons, multi-select boxes, text fields, file fields, etc.

  1. The form tag is a form tag, and the corresponding value can be obtained through the corresponding name attribute in the background.
  2. The action attribute sets the submitted server address
  3. The method attribute sets the submission method GET (default value) or POST

There are three situations in which the data is not sent to the server when the form is submitted:

  1. Form item has no name attribute value
  2. Both radio selection and check selection (option tag in the drop-down list) need to add the value attribute in order to send it to the server.
  3. The form item is not in the submitted form tag

Form submission features:

  1. The page will be refreshed every time it is submitted, and partial refresh cannot be achieved.
  2. Form submission will create a new page
  3. The form form comes with the browser, and you can submit the form regardless of whether js is enabled or not.
  4. There are verification fields in the attributes of the form. Easyui, jeecg, etc. are all encapsulated. The user only needs to add the verification rules of regular expressions.

for demonstration

2. Native ajax

The full name of Ajax is Asynchronous JavaScript and XML (that is, asynchronous JavaScript and XML). It is not a new language, but a combination of several original technologies. Generally speaking, ajax is a technology that can update parts of a web page without reloading the entire web page.

<h1>原生ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button>原生---get</button>
<button>原生---post</button>
<script>
    let getBtn = document.querySelectorAll('button')[0];
    let postBtn = document.querySelectorAll('button')[1];

    // 原生ajax-get
    getBtn.onclick = function () {
     
     
        // 1.创建请求对象

        let xhr = new XMLHttpRequest();
        // 2.创立链接
        xhr.open("get", `/login?name=${
       
       userName.value}&psw=${
       
       pswd.value}`, true)
        // 3.发送请求
        // xhr.setRequestHeader("Content-Type","applacation/json")
        // xhr.setRequestHeader("Content-Type","applacation/x-www-form-urlencoded")
        xhr.send();
        // 监听请求状态
        xhr.onreadystatechange = function () {
     
     
            if (xhr.readyState == 4 && xhr.status == 200) {
     
     
                console.log("ajax-get", xhr.responseText);
            }
        }
    }
    // 原生ajax-post
    postBtn.onclick = function () {
     
     
        // 1.创建请求对象

        let xhr = new XMLHttpRequest();
        // 2.创立链接
        xhr.open("post", "/register", true)
        // 3.发送请求
        xhr.send(`name=${
       
       userName.value}&psw=${
       
       pswd.value}`);
        // 监听请求状态
        xhr.onreadystatechange = function () {
     
     
            if (xhr.readyState == 4 && xhr.status == 200) {
     
     
                console.log("ajax-post", xhr.responseText);
            }
        }
</script>

We can compare the entire process of ajax request with the following small example

We use the analogy of the entire interaction process with the phone call process.

  1. First, if you have functionality in mobile js, first look for objects, such as date-related Date, Math, and for ajax, look for XMLHttpRequest.
  2. signal data network
  3. Enter the number on your mobile phone and click the dial button
  4. Monitor whether the call is smooth and there is signal. The connection cannot be connected. The other party is busy and no one is answering.

Advantages of ajax requests

  1. Through the asynchronous mode, the user experience is improved -------ajax is performed asynchronously when submitting, requesting, and receiving, and does not affect other parts of the page.
  2. Optimizes the transmission between the browser and the server, reduces unnecessary data round-trips, and reduces bandwidth usage.
  3. The ajax engine runs on the client and takes on part of the work originally performed by the server, thereby reducing service loading under large user volumes.

Disadvantages of ajax requests

  1. Ajax must be implemented with js, which causes debugging troubles and browser compatibility issues. Moreover, browsers that do not enable js cannot complete the operation.
  2. Browser back button is not supported
  3. ajax exposes details of interaction with server
  4. Weak search engine support

3. jQuery’s ajax

jQuery ajax parameters

type: request method
url: request address (backend data interface)
data: specifies the data to be sent to the server.
dataType: The data type of the server response.
success(result,status,xhr): callback function when successful. For
more parameters, you can check the novice tutorial or W3C

<h1>jQuery--ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button class="jqGet">jQ---get</button>
<button class="jqPost">jQ---post</button>
<!-- 这里要注意下你要引用的jQuery路径 -->
<script src="./jquery.min.js"></script>
<script>
// *****************jQ-get
    $('.jqGet').click(() => {
     
     
        $.ajax({
     
     
            type: "get",
            url: "/login",
            data: {
     
      name: userName.value, psw: pswd.value },
            // 注意这里是写数据类型,这里要么不写,要么写json
            dataType: "dataType",
            success: function (response) {
     
     
                console.log("jQ-get:", response);
            }
        });
    })
// *****************jQpost
    $('.jqPost').click(() => {
     
     
        $.ajax({
     
     
            type: "post",
            url: "/register",
            data: {
     
      name: userName.value, psw: pswd.value },
            success: function (response) {
     
     
                console.log("jQ-post:", response);
            }
        });
    })
</script>

4. axios

After Vue2.0, You Yuxi recommended that everyone use axios to replace JQuery ajax, which must have brought axios into the eyes of many people.
axios is an HTTP client based on Promise for browsers and nodejs. It is essentially an encapsulation of native XHR. However, it is an implementation version of Promise and complies with the latest ES specifications. It has the following characteristics:

1. Supports both browser-side and server-side requests.
2. Support Promise API
3. Support interception client for request and data return
4. Provide some interfaces for concurrent requests (important, convenient for many operations)
5. Cancel requests
6. Convert request return data and automatically convert JSON data
7. Supports preventing CSRF.
Note: Preventing CSRF means that each of your requests carries a key obtained from the cookie. According to the browser's same-origin policy, fake websites cannot obtain the key obtained from your cookie. In this way , the backend can easily identify whether the request is a misleading input from the user on a fake website, and thus adopt the correct strategy.

<h1>axios--ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button class="aGet">jQ---get</button>
<button class="aPost">jQ---post</button>
<!-- 这里要注意下你要引用的jQuery路径和axios路径 -->
<script src="./jquery.min.js"></script>
<script src="./axios.min.js"></script>
<script>
    // *****************axios-get
    $(".aGet").click(() => {
     
     
        axios.get("/login", {
     
     
            params: {
     
      name: userName.value, psw: pswd.value }
        }).then((response) => {
     
     
            // then就相当于success
            console.log("axios-get", response);
        })
    })
    // *****************axios-post
    $(".aPost").click(() => {
     
     
        // post请求  参数直接写{}   不需要外面那层params
        axios.post("/register", {
     
      
            name: userName.value, psw: pswd.value 
        }).then((response) => {
     
     
            // then就相当于success
            console.log("axios-post", response);
        })
    })
</script>

5. fetch

Fetch is known as a replacement for AJAX. It appeared in ES6 and uses the promise object in ES6. Fetch is designed based on promises. The code structure of Fetch is much simpler than ajax, and the parameters are a bit like jQuery ajax. However, you must remember that fetch is not a further encapsulation of ajax, but native js, which does not use the XMLHttpRequest object.
Advantages of fetch:
1. It conforms to the separation of concerns and does not mix input, output and status tracked by events in one object.
2. Better and more convenient writing method

At the end of the article, I will give you the five statuses of ajax requests.

0 - (Uninitialized) The send() method has not been called yet
1 - (Loading) The send() method has been called and the request is being sent
2 - (Loading completed) The send() method has been executed and all response content has been received
3 - (Interaction) Parsing response content
4 - (Complete) Response content parsing is completed and can be called on the client

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/118310656