The use of springboot Ajax

Time:2021-6-21

Ajax overview

What is Ajax?

Ajax (asynchronous JavaScript and XML) is a web application client technology. It can communicate with the server application asynchronously with the help of client script (multiple threads can interact with the server at the same time). After obtaining the server data on demand, it can refresh the data locally, so as to improve the response and rendering speed of the data.

Ajax application scenarios?

The biggest advantage of Ajax technology is that the bottom layer is asynchronous, and then local refresh, so as to improve the user experience

  • Commodity system.
  • Evaluation system.
  • Map system.
  • …..

Ajax can only send and retrieve the necessary data to the server, and use JavaScript to process the response from the server on the client side. In this way, the data exchanged between the server and the browser is greatly reduced, and the response speed of the server is faster. But Ajax technology also has disadvantages, the biggest disadvantage is that it can’t directly cross domain access.

Analysis of Ajax request response process

The traditional way is web request and response (the client has to wait for the response result), as shown in the figure:

The use of springboot Ajax

Ajax request and response (the key is that the client does not block), as shown in the figure:

The use of springboot Ajax

Ajax programming steps and template code analysis

The basic steps of Ajax coding( Focus on the entry of Ajax Technology (XMLHttpRequest XHR object)

Step 1: create XHR objects based on DOM events
Step 2: register status monitor on XHR object (monitor the communication process between client and server)
Step 3: establish a connection with the server (specify the request method, request URL, synchronous or asynchronous)
Step 4: send the request (send the request data to the server)

The template code of Ajax coding process is as follows:

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
    if(xhr.readyState==4&&xhr.status==200){
           console.log(xhr.responseText)
    }
}
xhr.open("GET",url,true);
xhr.send(null);

Application of Ajax in springboot project

Step 1: create project 13 springboot Ajax

The use of springboot Ajax
Step 2: add spring web dependency. The code is as follows:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 3: create an Ajax controller to process client requests. The code is as follows:

package com.cy.pj.ajax.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "Response Result Of Ajax Get Request 01 ";
    }
}

Step 4: create a page ajax-01.html in the static directory of the project. The code is as follows:

The HTML element code is as follows:

<h1>The Ajax 01 Page</h1>
<fieldset>
   < legend > Ajax asynchronous get request
   <button onclick="doAjaxStart()">Ajax Get Request</button>
   <span id="result">Data is Loading ...</span>
</fieldset>

The JavaScript script code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
    <div>
         <h1>The Ajax 01 Page</h1>
         < fieldset > < legend > Ajax asynchronous request < / legend >
         <button onclick="doAjaxGet()">Ajax Get Request</button>
         <span id="resultId">Loading data....</span>
         </fieldset>
     </div>
</body>
<script>
     function doAjaxGet() {
                debugger;
         //1. Create XHR object (this object is the entry object of Ajax technology application, sending asynchronous request and processing response results are realized through this object)
         var xhr = new XMLHttpRequest();
         //2. Set state monitoring
         XHR. Onreadystatechange = function() {// time listening function (processing data generated during the process of client and server passing)
         //ReadyState values 0, 1, 2, 3, 4
         //0 means that the open method has not been executed
         //1 means that the open method has been executed but the send method has not been executed
         //2 means that the send method has been executed
         //3 indicates that the client is receiving the data from the server
         //4 indicates that the client has finished receiving the response data
         //200 indicates that the processing of the server is OK
         if (xhr.readyState == 4 && xhr.status == 200) {
            var result = xhr.responseText;// Get the text data of the server response
            document.getElementById("resultId").innerHTML = result;
         }
                }
                //3. Establish the connection with the server
         xhr.open("GET", " http://localhost/doAjaxGet ", true);// True indicates an asynchronous request
         //4. Send the request
         xhr.send(null);// Give the request to the Ajax engine
            console.log("do other...");
     }
</script>
</html>

Step 5: start Tomcat service and conduct access test analysis
The use of springboot Ajax
ajax-02.html
Use of post and get:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <h1>The Ajax 02 Page</h1>
 < fieldset > < legend > Ajax form request < / legend >
 <form> <input type="text" name="name" id="nameId" class="mingzi" onblur="doCheck()"/>
 <button type="button" onclick="doSave()">Save</button>
 </form> <span id="result"></span>
 </fieldset></div>
<script>
 Function dosave() {// sends an asynchronous request to check whether the name exists
 //1. Create XHR object (the entrance of Ajax technology application)
 let xhr=new XMLHttpRequest();
 //2. Set state monitoring (it is not necessary, but if you want to get the result of server response and process it, you need to do state monitoring)
 xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                document.getElementById("result").innerHTML=xhr.responseText;
 }
        }
        //3. Establish a get connection (get requests to send parameters, which should be spliced into the URL)
 let name=document.forms[0].name.value;// Get the value attribute value corresponding to name in the form
 console.log("name",name);
 let url="http://localhost/doSave";
 xhr.open("POST",url,true);
 //If the post request needs to pass parameters to the server, the request header must be set after open
 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 //4. Send asynchronous post request (parameters need to be written inside the send method) - when the form data or the amount of data is large
 xhr.send(`name=${name}`);// The splicing URL is represented by Template Strings' ` and ${}
 }
    Function docheck() {// sends an asynchronous request to check whether the name exists
 //1. Create XHR object
 debugger;
 var xhr = new XMLHttpRequest();
 //2. Set state monitoring
 xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
 document.getElementById("result").innerHTML = result;
 }
        }
        //3. Establish a connection with the server. Get
 let name=document.forms[0].name.value;// Get the value attribute value corresponding to name in the form
 //let name=document.getElementById("nameId").value;// Based on node ID acquisition
 //let name=document.querySelector("#nameId").value;// Based on ID selector (prefix "#")
 //let name=document.querySelector(".mingzi").value;// Based on class selector (prefix ".")
 //let name=document.querySelector("input").value;  let url=` http://localhost :1314/doCheck?name=${name}`;// Splicing URLs by Template Strings' ` and ${}
 xhr.open("GET",url, true);
 //xhr.open("GET", "http://localhost/doCheck?name="+name, true);
 //4. Send the request
 xhr.send(null);// Give the request to the Ajax engine
 }
</script>
</body>
</html>

ajax-03.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <h1>The Ajax 03 Page</h1>
 < fieldset > < legend > Ajax form request < / legend >
 <form> <input type="text" name="name" id="nameId" class="mingzi" onblur="doCheck()"/>
 <button type="button" onclick="doSave()">Save</button>
 </form> <span id="result"></span>
 </fieldset></div>
<script>
 function doAjaxGet(url,params,callback){
            //1. Create XHR object
             debugger;
             var xhr = new XMLHttpRequest();
             //2. Set state monitoring
             xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
 document.getElementById("result").innerHTML = result;
 }
        }
        //3. Establish a connection with the server. Get
         xhr.open("GET",`${url}?${params}`, true);
         //4. Send the request
         xhr.send(null);// Give the request to the Ajax engine
         }
    function doAjaxPost(url,params,callback) {
        //1. Create XHR object(Ajax技术应用的入口)
         let xhr = new XMLHttpRequest();
         //2. Set state monitoring (it is not necessary, but if you want to get the result of server response and process it, you need to do state monitoring)
         xhr.onreadystatechange = function (callback) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                callback(xhr.responseText);
 }
        }
        //3. Establish a get connection (get requests to send parameters, which should be spliced into the URL)
         xhr.open("POST", url, true);
         //If the post request needs to pass parameters to the server, the request header must be set after open
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         //4. Send asynchronous post request (parameters need to be written inside the send method) - when the form data or the amount of data is large
         xhr.send(`name=${params}`);// The splicing URL is represented by Template Strings' ` and ${}
 }
        Function dosave() {// sends an asynchronous request to check whether the name exists
         //1. Define the request URL
         let url = "http://localhost:1314/doSave";
         let params = document.forms[0].name.value;// Get the value attribute value corresponding to name in the form
         doAjaxPost(url, params, function (result) {
                        document.getElementById("result").innerHTML = result;
         })
        }
        Function docheck() {// sends an asynchronous request to check whether the name exists
         let name = document.forms[0].name.value;// Get the value attribute value corresponding to name in the form
         let params = `name=${name}`;
         let url = ` http://localhost :1314/doCheck`;// Splicing URLs by Template Strings' ` and ${}
         doAjaxGet(url, params, function (result) {
                        document.getElementById("result").innerHTML = result;
         })
        }
</script>
</body>
</html>

axios-ajax-01.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <button onclick="doAxiosAjaxGet()">axios.get(...)</button>
 <button onclick="doAxiosAjaxPost()">axios.post(...)</button>
 <button onclick="doAxiosAjaxPostJSON()">axios.postJSON(...)</button>
</div>
<div class="result"></div>
<script></script>
<script>
 function doAxiosAjaxPostJSON(){
        //1,url
 let url="http://localhost/doPostJSON";
 //2,params
 let params={"msg":"hello axios"};
 //3,send axios ajax request
 axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
    function doAxiosAjaxPost(){
        //1,url
 let url="http://localhost/doPost";
 //2,params
 let params="msg=hello axios";
 //3,send axios ajax request
 axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
    function doAxiosAjaxGet(){
        //1,url
 let url="http://localhost/doAjax";
 //2,params
 let params={params: {"msg":"hello axios"}}
        //3,send ajax get request
 axios.get(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
</script>
</body>
</html>

jquery-ajax-01.html

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
    <div>
         <button onclick="doAxiosAjaxGet()">axios.get(...)          </button>
         <button onclick="doAxiosAjaxPost()">axios.post(...)</button>
         <button onclick="doAxiosAjaxPostJSON()">axios.postJSON(...)</button>
    </div>
    <div class="result"></div>
    <script></script>
    <script>
        function doAxiosAjaxPostJSON(){
            //1,url
             let url="http://localhost/doPostJSON";
             //2,params
             let params={"msg":"hello axios"};
             //3,send axios ajax request
             axios.post(url,params)
            .then(function (result){//callback function
            document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
    function doAxiosAjaxPost(){
        //1,url
             let url="http://localhost/doPost";
             //2,params
             let params="msg=hello axios";
             //3,send axios ajax request
             axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
    function doAxiosAjaxGet(){
        //1,url
             let url="http://localhost/doAjax";
             //2,params
             let params={params: {"msg":"hello axios"}}
                    //3,send ajax get request
             axios.get(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// Native JS code
 })
            .catch()
    }
</script>
</body>
</html>