1.什麼是ajax
1.Ajax全稱:Asynchronous JavaScript And XML
簡單來講就是通過ajax,你不需要重新刷新整個頁面就能實現對局部頁面的刷新操作。
2.AJAX的使用
//1.創建ajax對象
var xhr=new XMLHttpRequest();
2.監聽ajax對象
xhr.onreadystatechange=function(){}
3.打開對象
xhr.open()
4.發送請求
xhr.send()
ajax有get和post兩種方式發送請求,下面通過java和ajax模擬異步刷新。java方面以SpringBoot作爲後臺。
3.SpringBoot後臺的搭建
搭建SpringBoot後臺不是一件困難的事情,下圖是整個項目的結構圖
3.1 創建項目,引入依賴
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sdxb</groupId>
<artifactId>ajaxtest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2 編寫啓動類和配置文件
編寫SpringBoot的啓動類AjaxtextApplication
@SpringBootApplication
public class AjaxtestApplication {
public static void main(String[] args) {
SpringApplication.run(AjaxtestApplication.class);
}
}
所有html代碼均放在resource文件夾下的templates中,在application.properties文件中表明靜態文件路徑
spring.resources.static-locations=classpath:/templates/
spring.mvc.view.suffix=.html
3.3 編寫controller
新建indexController,首先寫一個簡單的方法,用於返回我們第一個靜態頁面index.html
@Controller
public class indexController {
@RequestMapping("/test")
public String index(){
return "index";
}
}
4.ajax的get請求
我們寫一個簡單的頁面,只包含一個按鈕和一行文本。然後通過ajax的get請求去後端請求一段數據,不斷刷新到文本處。下面是html代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="button" id="btn" value="button">
<h1>test</h1>
<script type="text/javascript">
var btn=document.getElementById("btn");
btn.onclick=function () {
//1.創建ajax對象
var xhr=new XMLHttpRequest();
//2.監聽ajax對象
xhr.onreadystatechange=function () {
/*
/當xhr對象的readystate屬性發生了改變,這個事件就會觸發
readyState:
0 ===>xhr對象已經創建,但是還沒有進行初始化操作
1===>xhr對象已經調用了open
2===)xhr已經發出ajax請求
3 ===>已經返回了部分數據
4===>數據已經全部返回
*/
if (xhr.readyState!=4){
return;
}
//如果請求沒有出錯則會返回200-300的狀態碼
if (xhr.status>=200&&xhr.status<=300){
document.getElementsByTagName("h1")[0].innerHTML+=xhr.responseText;
}
}
//3.打開對象,第三個參數表示是否使用異步
xhr.open("get","http://localhost:8080/test2",true);
//4.發送請求
xhr.send();
}
</script>
</body>
</html>
關鍵的ajax代碼處已經用註解標出。還需要在controller中處理http://localhost:8080/test2的請求,在indexController中添加以下代碼:
@GetMapping("/test2")
@ResponseBody
public String index2(HttpServletResponse response){
return "hello world";
}
運行項目,輸入http://localhost:8080/test,不斷點擊按鈕,不斷將文本刷新到頁面上:
5.ajax的post請求
通常需要提交數據的場景都會使用post請求,通過表單提交數據,因此就來模擬登陸的場景。爲了方便,我直接將用戶名和密碼寫在前端代碼中:login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="button" id="btn" value="button">
<h1>test</h1>
<script type="text/javascript">
var btn=document.getElementById("btn");
btn.onclick=function () {
//1.創建ajax對象
var xhr=new XMLHttpRequest();
//2.監聽ajax對象
xhr.onreadystatechange=function () {
/*
/當xhr對象的readystate屬性發生了改變,這個事件就會觸發
readyState:
0 ===>xhr對象已經創建,但是還沒有進行初始化操作
1===>xhr對象已經調用了open
2===)xhr已經發出ajax請求
3 ===>已經返回了部分數據
4===>數據已經全部返回
*/
if (xhr.readyState!=4){
return;
}
if (xhr.status>=200&&xhr.status<=300){
//處理後端傳送的json對象
var result=JSON.parse(xhr.responseText)
if (result.res==true){
document.getElementsByTagName("h1")[0].innerHTML="登陸成功";
} else {
document.getElementsByTagName("h1")[0].innerHTML="登陸失敗";
}
}
}
//3.打開對象
xhr.open("post","http://localhost:8080/test3",true);
//使用post請求需要爲xhr對象添加請求頭部
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//4.發送請求,數據寫在參數中
xhr.send("username=sdxb&password=123456");
}
</script>
</body>
</html>
@RequestMapping("/log")
public String login(){
return "login";
}
@PostMapping("/test3")
@ResponseBody
public Result index3(HttpServletRequest request,HttpServletResponse response){
String username=request.getParameter("username");
String password=request.getParameter("password");
Result result=new Result();
if (username.equals("sdxb")&&password.equals("123456")){
result.setRes(true);
return result;
}
else {
result.setRes(false);
return result;
}
}
這裏的Result對象是自己寫的類,只包含一個Res對象,當使用了@ResponseBody後,返回對象時會自動轉化成json對象傳遞給前端。