Several ways for the front end to send requests

1. form submission

<h1>form表单的get</h1>
<form action="/adress" method="get">
        <input type="text" name="name">
        <input type="text" name="pswd">
        <input type="submit" value="get">
 </form>
 <h1>form表单的post</h1>
 <form action="/adress" method="post">
        <input type="text" name="name">
        <input type="text" name="pswd">
        <input type="submit" value="post">
  </form>

The form form submits the content in the form to the background, such as input boxes, radio boxes, check boxes, text fields, etc.

  • The form form is submitted, and the corresponding value can be obtained through the corresponding name attribute in the background
  • The action attribute is used to set the submitted server address
  • The method attribute is used to set the submission method of the form form get or post, the default value is get

Features of Form Submission:

  • A new page will be created after the form form is submitted
  • Every submission will refresh the page, there is no way to refresh the page partially
  • The form form comes with the browser, even if the browser's js support is turned off, the form can still be submitted

2. Native ajax

Introduction (from MDN)

Asynchronous JavaScript + XML (asynchronous JavaScript and XML), itself 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 (en-US), XSLT, and most importantly XMLHttpRequest. When using the AJAX model combined with these techniques, web applications can quickly render incremental updates to the user interface without reloading (refreshing) the entire page. This allows the program to respond more quickly to user actions.

Although X stands for XML in Ajax, JSON is currently more commonly used than XML due to JSON's many advantages, such as being lighter weight and being part of Javascript. Both JSON and XML are used to package information in Ajax models.

brief summary

Ajax is not a new technology, but a combination of several technologies. Ajax can update part of the webpage without loading the entire page, which can make the program respond to the user faster

example

    <h1>原生ajax</h1>
    <input type="text" id="userName" value="hehe">
    <button id="getbtn">ajax--get</button>
    <input type="text" id="pswd">
    <button id="postbtn"></button>
    <script>
        let getBtn = document.querySelector('#getbtn');
        let postBtn = document.querySelector('#postbtn');
        let userName = document.querySelector('#userName');
        let pswd = document.querySelector('#pswd');

        // 原生ajax-get
        getBtn.onclick = function () {
            // 1.创建请求对象
            let xhr = new XMLHttpRequest();
            // 2.创立链接
            xhr.open("get", `/login?name=${userName.value}&pswd=${pswd.value}`, true)
            // 3.发送请求
            xhr.send();
            // 4.监听请求状态
            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}&pswd=${pswd.value}`);
            // 4.监听请求状态
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log("ajax-post", xhr.responseText);
                }
            }
        }
    </script>

Advantages of ajax requests

  • Ajax is asynchronous when submitting, requesting, and receiving, and will not affect other parts of the page, which improves the user experience

Disadvantages of ajax requests

  • The steps are cumbersome to use
  • Does not support browser back button
  • Ajax exposes the details of interaction with the server

Three jQuery ajax

Why is it jQuery's ajax? jQuery just encapsulates native ajax, so you don't have to write native ajax every time, which is convenient for programmers.

 $('#getbtn').click(() => {
        $.ajax({
            type: "get",
            url: "/login",
            data: { name: userName.value, pswd: pswd.value },
            // 注意这里是写数据类型,这里要么不写,要么写json
            dataType: "dataType",
            success(response) {
                console.log("get:", response);
            }
        });
    })
    $('#postbtn').click(() => {
        $.ajax({
            type: "post",
            url: "/register",
            data: { name: userName.value, pswd: pswd.value },
            success(response) {
                console.log("post:", response);
            }
        });
    })

jQuery ajax parameters

  • type: request method
  • url: request address
  • data: the data sent to the server
  • dataType: the data type of the server response
  • success(response, status, xhr): callback when successful

Note that you need to introduce jQuery to use

Four: axios

Introduction (from Axios official website)

Axios is a promise-based network request library for node.js and the browser. It is isomorphic (ie the same code can run in the browser and node.js). On the server side it uses the native node.js http module, and on the client side (browser side) it uses XMLHttpRequests.

example

   // *****************axios-get

        axios.get("/login", {
            params: { name: userName.value, pswd: pswd.value }
        }).then((response) => {
            // then就相当于success
            console.log("axios-get", response);
        })
 
 
    // *****************axios-post
   
        // post请求  参数直接写{}   不需要外面那层params
        axios.post("/register", { 
            name: userName.value, psw: pswd.value 
        }).then((response) => {
            // then就相当于success
            console.log("axios-post", response);
        }

You Yuxi, the creator of the vue framework, recommends using axios to replace jQuery

  • The configuration and calling methods of native ajax are very cumbersome, and it is troublesome to implement asynchronous requests
  • jQuery's ajax is very useful compared to native ajax, but there is no need to refer to the entire jQuery framework because of the ajax asynchronous network

Axios is essentially an encapsulation of native ajax, but it is the implementation version of Promise. Compared with native ajax or jQuery ajax, programmers save the process of creating Promise objects, which conforms to the latest ES specification. It has the following characteristics:

  • Support both browser-side and server-side requests
  • Support promise API
  • Provides some interfaces for concurrent requests
  • Conversion request returns data, automatically converted to JSON format

Five. fetch

Introduction (from MDN)

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 that provides an easy, sensible way to fetch resources asynchronously across the network.

This functionality was previously implemented using XMLHttpRequest. Fetch provides a more desirable alternative that can easily be used by other technologies such as Service Workers. Fetch also provides a dedicated logical space to define other HTTP-related concepts, such as CORS and HTTP extensions.

example


//发起get请求
fetch(url).then(function(response) {

   //response.status表示响应的http状态码
   if(response.status === 200){
     //json是返回的response提供的一个方法,会把返回的json字符串反序列化成对象,也被包装成一个Promise了
     return response.json();
   }else{
     return {}
  }
});



//fetch post请求
fetch(url, {
    method: 'post',
    body: JSON.stringify(base),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(function(data) {
 
 
  })

Fetch claims to be an ajax substitute, which appeared in ES6 and uses the promise object in ES6. Fetch is designed based on promises. Fetch's code structure is much simpler than ajax, and the parameters are a bit like jQuery ajax. However, fetch is not a further encapsulation of ajax, but native js, without using the XMLHttpRequest object.

Guess you like

Origin blog.csdn.net/Angel_Tears_/article/details/127218747