编程知识 cdmana.com

Analysis and application of Ajax technology in 14 spring boot project

Ajax Technical introduction

Background analysis ?

Today, with the rapid development of Internet , Conventional WEB application , For high concurrency 、 High performance 、 The demand for high reliability is imminent . Single thread mode of client-side and server-side interaction mode has been unable to meet the needs of the current stage . We need to be asynchronous 、 Load on demand to get data from the server and refresh in time , To improve the user experience , therefore Ajax The birth of Technology .

Ajax What is it? ?

Ajax (Asynchronous JavaScript and XML) It's a kind of Web Application client technology , You can use client script (javascript) Asynchronous communication with server applications ( Multiple threads can interact with the server at the same time ), And after getting the server-side data on demand , Local refresh can be done , In order to improve the data response and rendering speed .

Ajax Application scenarios ?

Ajax The biggest advantage of technology is the underlying asynchronous , Then partial refresh , To improve the user experience , This technology is now well used in many projects , for example :

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

AJAX You can just send and retrieve the necessary data to the server , And in the client side JavaScript Processing the response from the server . This reduces the amount of data exchanged between the server and the browser , The server responds faster . but Ajax Technology also has disadvantages , The biggest disadvantage is that cross domain access is not available directly .

Ajax Application model analysis ?

Ajax Quick start

Ajax Request response process analysis

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

image.png

Ajax How to request and respond ( The key is that the client does not block ), As shown in the figure :

image.png

Ajax Programming steps and template code analysis

Ajax The basic steps of coding ?( The key is ajax The entrance of Technology -XMLHttpRequest-XHR object )

First step : be based on dom Event creation XHR object
The second step : stay XHR Register state listener on object ( Monitor the communication process between client and server )
The third step : Establish a connection with the server ( Specify request method , request url, Synchronous or asynchronous )
Step four : Send a request ( Pass the request data to the server )

Ajax The template code for the encoding 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);

SpringBoot project Ajax Introduction analysis of technology application

First step : Create project module, As shown in the figure :

image.png

The second step : add to Spring web rely on , The code is as follows :

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

The third step : establish AjaxController Handle 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 four : In the project static Under the table of contents , Create a page ajax-01.html, The code is as follows :

html The element code is as follows :

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

javascript The script code is as follows :

function doAjaxGet01(){
 //debugger// Client breakpoints ( This breakpoint takes effect by opening the console )
 //1. establish XHR object (XmlHttpRequest)-Ajax The entry object of the application 
 let xhr=new XMLHttpRequest();
 //2. stay XHR Register state listener on object ( Get the server response results and update to the page result Location )
 xhr.onreadystatechange=function(){// Event handler ( The communication state between the client and the server changes    This function is executed when )
 //readyState==4 Indicates that the server responds that the client data has been received .
 if(xhr.readyState==4){
            if(xhr.status==200){//status==200 Indicates that the request processing is OK 
               document.getElementById("result").innerHTML=
                    xhr.responseText;
            }
        }
 }
 //3. Establish a connection with the server ( Specify request method , request url, asynchronous )
 xhr.open("GET","http://localhost/doAjaxStart",true);//true On behalf of the asynchronous 
 //4. Send a request to the server 
 xhr.send(null);//get request send Methods do not transfer data or write a null
 console.log("===main thread===")
// If it is an asynchronous client, the execution is finished send Will continue down .
}

Step five : start-up Tomcat Service and access test analysis .

image.png

Click on Ajax Get Request Button , Detect page data updates .

Step six : During the start-up and access process Bug analysis

  • There is no response when you click the button

image.png

  • The object accessing the specified property does not exist

image.png

  • Cross domain access

image.png

Ajax Basic business implementation

Basic business description

Based on the ajax Technical understanding , Realization ajax The way of Get,Post,Put,Delete Wait for the request to be processed asynchronously , As shown in the figure :
image.png

The key code design and implementation of the server

Based on business description , stay AjaxController Class to add related properties and methods , For processing clients ajax request .

Add properties and constructors , The code is as follows :

/** Suppose this is a database for storing data */
    private List<Map<String,Object>> dbList=new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map=new HashMap<>();
        map.put("id","100");
        map.put("name"," Household appliances ");
        map.put("parentId",null);//parentId by null It means that it is 1 Class classification 
        map.put("remark"," Electrical appliances, etc ");
        map.put("createdTime",new Date());
        dbList.add(map);
    }

add to Ajax Request processing method , The code is as follows :

 @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return dbList;
    }
    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        map.put("createdTime",new Date());
        dbList.add(map);
        return "save ok";
    }
    @DeleteMapping("/doAjaxDelete")
    public String doAjaxDelete(String id){
        // Get iterator object , Then iteration list aggregate , find id Corresponding elements , Delete operation 
        Iterator it=dbList.iterator();
        while(it.hasNext()){
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(id)){
                //dbList.remove(map);// In this way, a concurrent deletion exception will occur 
                it.remove();// Delete through iterators 
            }
        }
        return "delete ok";
    }
    
    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> updateMap){
        Iterator it=dbList.iterator();
        while(it.hasNext()){
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(updateMap.get("id"))){
               map.put("name",updateMap.get("name"));
               map.put("remark",updateMap.get("remark"));
            }
        }
       return "update ok";
    } 

Client key code design and implementation

stay static Create under directory ajax-02.html file , The key codes are as follows :

<h1>The Ajax 02 Page</h1>
<button onclick="doAjaxGet()">Do Ajax Get</button>
<button onclick="doAjaxPost()">Do Ajax Post</button>
<button onclick="doAjaxDelete()">Do Ajax Delete</button>
<button onclick="doAjaxUpdate()">Do Ajax Update</button>
<div id="result"></div>

client JavaScript Script design , The code is as follows :

  • Get Request mode , The code is as follows :
 function doAjaxGet(){
       let xhr=new XMLHttpRequest();
       xhr.onreadystatechange=function(){
           if(xhr.readyState==4){
               if(xhr.status==200){
                  document.getElementById("result").innerHTML=xhr.responseText;
               }
           }
       }
       xhr.open("GET","http://localhost/doAjaxGet",true);
       xhr.send(null);
    }
  • Post Request mode , The code is as follows :
function doAjaxPost(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("POST","http://localhost/doAjaxPost",true);
        //post Request to pass data to the server , Need to set request header , Must be in open after 
 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // Send a request (post Request delivery data , Write data to send Methods the internal )
 xhr.send("id=101&name=Computer&remark=Computer...");
    }
  • Update Request mode , The code is as follows :
 function doAjaxUpdate(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("put","http://localhost/doAjaxUpdate",true);
        //post Request to pass data to the server , Need to set request header , Must be in open after 
 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // Send a request (post Request delivery data , Write data to send Methods the internal )
 xhr.send("id=101&name=Book&remark=Book...");
    }
  • Delete Request mode , The code is as follows :
 function doAjaxDelete(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("delete","http://localhost/doAjaxDelete?id=101",true);
        xhr.send(null);
    } 

Start the service for access test analysis

Ajax Advanced technology implementation

Ajax Encapsulation of code

In actual programming, we usually encapsulate code commonalities , Extract code features . Then to improve the reusability of the code . for example :

 function ajaxGet(url,params,callback) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("GET",params?url+"?"+params:url,true);
    xhr.send(null);
}

function ajaxPost(url,params,callback) {//add
 let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
}

function ajaxPut(url,params,callback) {//update
 let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("PUT",url,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
}

function ajaxDelete(url,params,callback) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("delete",params?url+"?"+params:url,true);
    xhr.send(null);
} 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> The Ajax 03 Page</h1>
<button onclick="doAjaxGet()">Do Ajax Get</button>
<button onclick="doAjaxPost()">Do Ajax Post</button>
<button onclick="doAjaxDelete()">Do Ajax Delete</button>
<button onclick="doAjaxUpdate()">Do Ajax Update</button>
<div id="result"></div>
<script src="/js/ajax.js"></script>
<script>
    //Get request 
 function doAjaxGet(){
       let url="http://localhost/doAjaxGet";
        let params="";
        ajaxGet(url,params,function (result){
           document.getElementById("result").innerText=result;
            // alert(result);
 // doAjaxGet(); })
    }
    //Post request 
 function doAjaxPost(){
        let url="http://localhost/doAjaxPost";
        let params="id=11&name=Computer&remark=Computer...";
        ajaxPost(url,params,function (result){
            document.getElementById("result").innerText=result;
            // alert(result);
 // doAjaxPost(); })
    }
    //Delete request 
 function doAjaxDelete() {
        let url="http://localhost/doAjaxDelete";
        let params="id=11";
        ajaxDelete(url,params,function (result){
            document.getElementById("result").innerText=result;
            // alert(result);
 // doAjaxDelete(); })
    }
    //Update request 
 function doAjaxUpdate(){
       let url="http://localhost/doAjaxUpdate";
        let params="id=11&name=TV&remark=TV...";
        ajaxPut(url,params,function (result){
            document.getElementById("result").innerText=result;
            // alert(result);
 // doAjaxUpdate(); })
    }
</script>
</body>
</html>

Ajax The implementation of small programming framework ( understand )

We're actually js Programming is often implemented in an object-oriented way , for example ajaxGet function , How to call as an object ? The key code analysis is as follows :( The following code understanding needs to have JS The basic knowledge of object-oriented in , If you are not familiar with it, you can skip it temporarily )

(function(){
    // Define a function , It can be connected as java Class in 
     var ajax=function(){}
    // In variables ajax Add a member to the class pointed to , for example doAjaxGet function ,doAjaxPost function 
     ajax.prototype={
        ajaxGet:function(url,params,callback){
        // establish XMLHttpRequest object , Send a request based on this object 
        var xhr=new XMLHttpRequest();
        // Set status monitoring ( Monitor the status of communication between client and server )
        xhr.onreadystatechange=function(){// Callback function , Event handler 
            if(xhr.readyState==4&&xhr.status==200){
                //console.log(xhr.responseText);
                callback(xhr.responseText);//jsonStr
            }
        };
        // Establishing a connection ( The request method is Get, request url, Asynchronous or synchronous -true Represents asynchrony )
        xhr.open("GET",url+"?"+params,true);
        // Send a request 
        xhr.send(null);//GET request send Methods don't write content 
     },
        ajaxPost:function(url,params,callback){
        // establish XMLHttpRequest object , Send a request based on this object 
        var xhr=new XMLHttpRequest();
        // Set status monitoring ( Monitor the status of communication between client and server )
        xhr.onreadystatechange=function(){// Callback function , Event handler 
            if(xhr.readyState==4&&xhr.status==200){
                    //console.log(xhr.responseText);
            callback(xhr.responseText);//jsonStr
            }
        };
        // Establishing a connection ( The request method is POST, request url, Asynchronous or synchronous -true Represents asynchrony )
        xhr.open("POST",url,true);
       //post This request header must be set when requesting parameter transmission 
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        // Send a request 
        xhr.send(params);//post request send Method 
        }
    }
    window.Ajax=new ajax();// structure ajax Object and assign it to variables, global variables Ajax
})()

At this point, the outside world calls doAjaxGet and doAjaxPost Function time , You can go directly through Ajax Object to implement .

Ajax Technology in Jquery Application in

Jquery brief introduction

jQuery It's a fast one 、 concise JavaScript Library framework , Is an excellent one JavaScript The code base ( or JavaScript frame ).jQuery The purpose of the design is “write Less,Do More”, That is to say, write less code , Do more . It encapsulates JavaScript Common function codes , Provides a simple JavaScript Design patterns , Optimize HTML The document operation 、 Event handling 、 Animation design and Ajax Interaction .

Jquery Commonly used ajax Function analysis

jQuery Based on standards ajax api Provides a wealth of Ajax Function application , Based on these functions, you can write a small amount of code , It can be realized quickly Ajax operation . Common functions are :

  • ajax(…)
  • get(…)
  • getJSON(…)
  • post(…)

explain :jquery in ajax For the syntax of related functions, please refer to the official website (jquery.com).

Jquery in Ajax The basic application implementation of function

Refer to the official case ....

summary (Summary)

This chapter mainly introduces Ajax What is it? 、 Application scenarios 、 The communication model between client and server 、ajax The basic steps of programming 、 Packaging process and ajax Technology in some JS Applications in the framework, etc , And focus on the analysis in ajax Some debugging skills in the coding process .

版权声明
本文为[Xiao Han]所创,转载请带上原文链接,感谢

Scroll to Top