時間:2022-03-01來源:www.outletmksalestore.com作者:電腦系統城
Ajax 的英文全稱是 ”Asynchronous JavaScript and XML“,即 ”異步的 JavaScript 和 XML“。其核心是通過 JavaScript 的 XMLHttpRequest 對象,以一種異步的方式,向服務器發送數據請求,并且通過該對象接收請求返回的數據,從而實現客戶端與服務器端的數據交互。
優點:Ajax 能夠刷新指定的頁面區域(局部刷新),而不是刷新整個頁面,從而減少客戶端和服務器端之間的數據交互傳輸,提高頁面速度,使得用戶體驗更好。
初體驗:基于 jQuery 方式動態綁定事件提交
給【獲取驗證碼】按鈕綁定點擊事件,當用戶點擊該按鈕時,向后臺服務器發送 AJAX 請求獲取一個隨機驗證碼,登錄頁面的整體不重新加載,僅做局部的頁面刷新。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >異步請求</ title > < script type = "text/javascript" src = "/static/js/jquery-2.0.0.min.js" ></ script > < script type = "text/javascript" > $(function () { var btn = $("#flush"); btn.click(function () { $.ajax({ url: '/getCode', type:'get', data:'id=1', //字符串 dataType:'text', success:function (data) { console.log(data); alert("后臺驗證碼:" + data); } }) }) }) </ script > </ head > < body > < div style = "text-align: center;" > < h2 >用戶登錄</ h2 > < form > 用戶名:< input type = "text" name = "username" >< br > 密 碼:< input type = "password" name = "password" >< br > 驗證碼:< input type = "text" name = "code" >< br >< br > < input type = "button" value = "登錄" > < input type = "button" id = "flush" value = "獲取驗證碼" > </ form > </ div > </ body > </ html > |
SpringBoot 后臺接收 AJAX 請求,首先要獲取該請求攜帶的參數 id=1
(該參數沒有實際意義,僅做演示使用),然后根據請求業務,對該結果進行響應。success
回調函數對響應結果進行展示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import javax.servlet.http.HttpServletRequest; import java.util.Random; @Controller public class TestController { @GetMapping ( "/ajax" ) public String index(){ return "form" ; } //SpringBoot接收ajax請求的方式 //方式一:使用HttpServletRequest request接收請求參數 @GetMapping ( "/getCode" ) @ResponseBody public String getCode(HttpServletRequest request){ String id = request.getParameter( "id" ); System.out.println( "AJAX傳遞的參數:" + id); //獲取5位驗證碼 return randomCodes(); } //方式二:用@Param映射單個值 @GetMapping ( "/getCode1" ) @ResponseBody public String getCode1( @Param ( "id" ) Integer id){ System.out.println(id); //獲取5位驗證碼 return randomCodes(); } public String randomCodes(){ String str= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ; StringBuilder code= new StringBuilder( 5 ); for ( int i= 0 ;i< 5 ;i++) { char ch=str.charAt( new Random().nextInt(str.length())); code.append(ch); } return code.toString(); } } |
上面介紹了兩種 SpringBoot 接收請求參數的方式:
public String getCode(HttpServletRequest request)
:使用 HttpServletRequest request 接收請求參數;public String getCode1(@Param("id") Integer id)
:用 @Param 映射單個值;Ajax 異步請求一個典型的應用就是用戶表單輸入時,局部刷新驗證碼,而不會影響其他表單項已輸入的信息。
傳統的 WEB 數據交互與 AJAX 數據交互比較:
$.ajax({屬性})
常用的屬性參數:
參數 | 描述 |
---|---|
url | 請求后端服務器的地址 |
type | 請求方式,默認為 get 類型 |
data | 請求參數 |
dataType | 服務器返回的數據類型,比如:text/json/xml 等 |
success | 請求成功的回調函數 |
error | 請求失敗的回調函數 |
complete | 請求完成的回調函數(無論成功還是失敗,都會被調用) |
用法示例(服務器與客戶端之間的數據交互類型是JSON):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$.ajax({ url: '/search' , type: 'post' , data:{ 'id' :$( "#sid" ).val(), 'username' :$( "#uname" ).val(), 'password' :$( "#pwd" ).val() }, dataType: 'json' , success: function (data) { console.log(data); $( "#sid" ).val(data.id); $( "#uname" ).val(data.name); $( "#score" ).val(data.score); } }) |
JSON(JavaScript Object Notation),一種輕量級數據交互格式,完成 js 與 Java/Python/PHP 等后端開 發語言對象數據之間的轉換??蛻舳伺c服務器之間傳遞對象數據時,需要使用 JSON 格式。
案例:使用 AJAX 校驗用戶輸入的信息,編寫一個 2022 年碩士研究生招生考試成績查詢系統;
1、創建空白的 SpringBoot 項目,并在 pom.xml 導入相關依賴;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-thymeleaf</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > < dependency > < groupId >com.baomidou</ groupId > < artifactId >mybatis-plus-boot-starter</ artifactId > < version >3.4.2</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >5.1.46</ version > </ dependency > |
2、在 MySQL 數據庫中創建一張考研成績數據表(stu_score),并錄入若干條測試數據;
3、在全局配置文件 resources/application.yml 中配置數據源信息、視圖解析器以及端口號等相關配置等;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 datasource: url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver mvc: static-path-pattern: /static/** server: port: 8181 # 配置SQL日志 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl |
4、創建數據表對應的實體類 Student;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.trainingl.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @TableName (value = "stu_score" ) public class Student { @TableId (type = IdType.ASSIGN_ID) private Long sid; private String sname; private String card; private Integer politics; private Integer english; private Integer math; private Integer computer; } |
5、在路徑 com > trainingl > mapper 下創建接口 StudentMapper;
1 2 3 4 5 6 7 8 9 10 |
package com.trainingl.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.trainingl.entity.Student; import org.springframework.stereotype.Repository; @Repository public interface StudentMapper extends BaseMapper<Student> { //所有的CRUD操作都已經編寫好了 } |
說明:由于系統規模較小,所以這里省略了 Service 服務層。
6、創建 SearchController 控制器,主要負責接收客戶端瀏覽器的 AJAX 請求與響應。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package com.trainingl.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.trainingl.entity.Student; import com.trainingl.mapper.StudentMapper; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping ( "/suda" ) public class SearchController { @Autowired private StudentMapper studentMapper; @GetMapping ( "/search" ) public String home(){ return "login" ; } @PostMapping ( "/login" ) @ResponseBody public Map<String,String> login(HttpServletRequest request){ String id = request.getParameter( "id" ); String username = request.getParameter( "username" ); String card = request.getParameter( "password" ); //查詢判斷 QueryWrapper<Student> wrapper = new QueryWrapper<>(); wrapper .eq( "sid" ,id) .eq( "sname" , username) .eq( "card" , card); Integer count = studentMapper.selectCount(wrapper); //返回值 HashMap<String, String> map = new HashMap<>(); if (count == 1 ){ //登錄驗證成功,通過id查詢該考生的成績(id具有唯一性) map.put( "result" , id); map.put( "code" , "100" ); } else { map.put( "result" , "登錄失??!輸入信息有誤!" ); map.put( "code" , "200" ); } return map; } @GetMapping ( "/searchById/{id}" ) public ModelAndView searchById( @PathVariable Long id){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName( "person" ); Student student = studentMapper.selectById(id); System.out.println(student); Integer total = student.getPolitics() + student.getEnglish() + student.getMath() + student.getComputer(); modelAndView.addObject( "student" , student); modelAndView.addObject( "totalScore" , total); return modelAndView; } } |
7、視圖層(系統登錄頁面、成績查詢頁面)
7.1 系統登錄頁面(客戶端與服務器之間的數據交互格式是JSON,請求方式是AJAX,而不是通過form表單完成)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >系統登錄</ title > < script type = "text/javascript" src = "/static/js/jquery-2.0.0.min.js" ></ script > < script type = "text/javascript" > $(function () { var btn = $("#btn"); // 點擊事件 btn.click(function () { $.ajax({ url:'/suda/login', type:'post', data:{ 'id':$("#sid").val(), 'username':$("#uname").val(), 'password':$("#pwd").val() }, dataType:'json', success:function (data) { if(data.code == "100"){ //登錄成功,則跳轉到成績查詢頁面 window.location.href = "/suda/searchById/" + data.result; }else{ //登錄失敗,則給出提示信息 var msg = $("#btn"); msg.after("< br >< br >< span style = 'color:red;' >提示:"+data.result+"</ span >") } } }) }) }) </ script > </ head > < body > < div style = "text-align:center;" > < img src = "/static/img/brand.png" style = "width: 280px;height: 100px;" /> < h3 >2022年碩士研究生招生考試成績查詢系統</ h3 > < img src = "/static/img/logo.jpeg" style = "width: 500px;height: 300px;" /> <!--這里不通過form表單提交客戶端請求--> < form > 準考證號:< input type = "text" name = "id" id = "sid" >< br > 考生姓名:< input type = "text" name = "username" id = "uname" >< br > 身份證號:< input type = "text" name = "password" id = "pwd" >< br /> < br /> < input type = "button" value = "查詢" id = "btn" > </ form > </ div > </ body > </ html > |
注:如果輸入的信息校驗失敗,則通過紅色字體給出提示,若信息校驗成功,則會跳轉到初試成績的詳細界面。
7.2 成績詳細頁面(通過 thymeleaf 模板渲染數據)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> < html lang = "en" xmlns:th = "http://www.w3.org/1999/xhtml" > < html xmlns:th = "http://www.thymeleaf.org" ></ html > < head > < meta charset = "UTF-8" > < title >研究生初試成績查詢</ title > </ head > < body > < div style = "text-align: center;" > < div style = "border: 1px solid;" > < h3 >2022年研究生考試初始成績查詢</ h3 > < br > 準考證號:< span th:text = "${student.sid}" ></ span >< br > 姓名:< span th:text = "${student.sname}" ></ span >< br > 身份證號:< span th:text = "${student.card}" ></ span >< br > < hr /> 思想政治理論:< span th:text = "${student.politics}" ></ span >< br > 英語(一):< span th:text = "${student.english}" ></ span >< br > 數學(一):< span th:text = "${student.math}" ></ span >< br > 計算機科學專業基礎(408):< span th:text = "${student.computer}" ></ span >< br > 總分:< span th:text = "${totalScore}" ></ span >< br > </ div > < p >說明:若查詢的成績為負值,表示有缺考、違紀等情況。若仍對查詢結果有疑問,請咨詢相應的招生單位。 </ p > </ div > </ body > </ html > |
總結:本項目用于演示 AJAX 與 SpringBoot 項目前后端數據交互,以案例+項目驅動的方式介紹了在 SpringBoot 項目開發中異步請求前后端數據的傳遞方式。
到此這篇關于AJAX SpringBoot 前后端數據交互的項目實現的文章就介紹到這了!
2022-03-01
Java PTA 計算3到7位 水仙花數實例2020-10-22
關于idea無法修改模板中jdk版本問題2020-10-07
系統城帶你使用SpringBoot基于WebSocket的在線群聊實現