Asynchronous interaction between front and back end – Ajax

Ajax

1. Introduction to Ajax

1, Ajax Overview

Ajax: The full name is Asynchronous JavaScript And XML, asynchronous JavaScript and XML. Its role has the following 2 points:

  • Data exchange with the server: through Ajax, you can send a request to the server and get the data that the server responds to.
  • Asynchronous interaction: A technology that can exchange data with the server and update some webpages without reloading the entire page, such as our input keywords in the browser When the time comes, there will be intelligent recommendations below.

2, Ajax role

Explain in detail the two functions of Ajax technology

  • Data interaction with the server

    As shown in the figure below, the front-end resources are parsed by the browser, but there is a lack of data on the front-end page. The front-end can initiate a request to the background server through Ajax technology. The background server receives the front-end request, obtains the resources needed by the front-end from the database, and then responds to the The front end, through the vue technology we learned, can display data on the page, so that users can see the complete page. Here it can be understood by comparing the network programming technology in JavaSE.

  • Asynchronous interaction: A technique that can exchange data with a server and update parts of a page without reloading the entire page.

    As shown in the figure below, when we search for java on Baidu, the following Lenovo data is obtained from the background server through Ajax requests. During the whole process, our Ajax requests will not cause the entire Baidu page to be reloaded, and it is only for search The data of this part of the module in the column is updated, and the data in other parts of the entire page will not be updated, which greatly improves the loading speed of the page and improves the user experience.

3, synchronous request and asynchronous request

The partial refresh function for the above-mentioned Ajax is because the Ajax request is asynchronous, and there is a synchronous request corresponding to it. Next, let’s introduce the difference between asynchronous requests and synchronous requests.

  • The synchronous request sending process is shown in the following figure:

The browser page is sending a request to the server, and the browser page cannot perform other operations while the server is processing the request. Only after the end of the server response can the browser page continue to do other operations.

  • The asynchronous request sending process is shown in the following figure:

The browser page sends a request to the server, and the browser page can also perform other operations while the server is processing the request.

2. Native Ajax

<!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>Native Ajax</title>
</head>
<body>
    
    <input type="button" value="Get Data" onclick="getData()">

    <div id="div1"></div>
    
</body>
<script>
    function getData(){<!-- -->
     //1. Create XMLHttpRequest
var xmlHttpRequest = new XMLHttpRequest();
        //2. Send an asynchronous request
        xmlHttpRequest.open('GET','http://yapi.smart-xwork.cn/mock/169327/emp/list');
        xmlHttpRequest.send();//Send request
        //3. Get service response data
xmlHttpRequest.onreadystatechange = function(){<!-- -->
    //The judgment here is 4 means that the browser has fully accepted the response from the Ajax request, and 200 means that this is a correct Http request without errors
    if(xmlHttpRequest.readyState == 4 & amp; & amp; xmlHttpRequest.status == 200){<!-- -->
        document.getElementById('div1').innerHTML = xmlHttpRequest.responseText;
    }
}
    }
</script>
</html>

Finally, we open the page through the browser, request to click the button, and send an Ajax request, and the final display result is shown in the following figure:

And through the f12 packet capture of the browser, we clicked on the XHR request in the network and found that the Ajax request we sent could be captured. XHR stands for asynchronous request

3. Getting Started with Axios

The above-mentioned native Ajax request code is relatively cumbersome to write, so let’s learn a simpler technology for sending Ajax requests, Axios. Axios encapsulates native AJAX to simplify writing. Axios official website is: https://www.axios-http.cn

Basic usage

The use of Axios is relatively simple, mainly divided into 2 steps:

  • Import Axios file
<script src="js/axios-0.18.0.js"></script>
  • Use Axios to send requests and get response results. There are many official APIs. Here are two types, as follows

    • send get request

      axios({<!-- -->
          method: "get",
          url: "http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan"
      }).then(function (resp){<!-- -->
          alert(resp. data);
      })
      
    • send post request

      axios({<!-- -->
          method: "post",
          url: "http://localhost:8080/ajax-demo1/aJAXDemo1",
          data: "username=zhangsan"
      }).then(function (resp){<!-- -->
          alert(resp. data);
      });
      

    axios() is used to send asynchronous requests, and the JSON object of js is used in parentheses to pass request-related parameters:

    • method attribute: used to set the request method. The value is get or post.
    • url attribute: the resource path used to write the request. If it is a get request, the request parameters need to be spliced to the back of the path, the format is: url?parameter name=parameter value & amp;parameter name2=parameter value2.
    • data attribute: the data sent as the request body. That is to say, if it is a post request, the data needs to be used as the value of the data attribute.

    then() needs to be passed an anonymous function. We call the anonymous function passed in then() the callback function, which means that the anonymous function will not be called when the request is sent, but a function that is called after a successful response. The resp parameter in the callback function is an object that encapsulates the response data, and the response data can be obtained through resp.data.

Quick Start

Then introduce the js file that axios depends on in the html, and provide 2 buttons, bind the click event, and send the ajax request when clicking, the complete code is as follows:




    
    
    
    Ajax-Axios
    <script src="js/axios-0.18.0.js"></script>


    
    

    




Request method alias

Axios also provides alias APIs for different requests, as follows:

Method Description
axios.get(url [, config ]) Send get request
axios.delete(url [, config]) Send delete request
axios.post(url [, data[, config]]) Send post request
axios. put(url [, data[, config]]) send put request

We currently only focus on get and post requests, so in the above case, we can rewrite the get request code as follows:

axios.get("http://yapi.smart-xwork.cn/mock/169327/emp/list").then(result => {<!-- -->
    console.log(result.data);
})

The post request is rewritten as follows:

axios.post("http://yapi.smart-xwork.cn/mock/169327/emp/deleteById","id=1").then(result => {<!-- -->
    console.log(result.data);
})

We often cooperate with the “hook function” in Vue to make asynchronous requests to the background:

Roughly as follows:

<script>
    new Vue({<!-- -->
       el: "#app",
       data: {<!-- -->
         emps:[]
       },
       mounted () {<!-- -->
          //Send asynchronous request, load data
          axios.get("http://yapi.smart-xwork.cn/mock/169327/emp/list").then(result => {<!-- -->
            console.log(result.data);
            this.emps = result.data.data;
          })
       }
    });
</script>