jquery ajax load()
应用:使用异步请求加载静态页面,也可从后端控制器获取数据
********************
语法:load(url,[data],[callback])
url:请求加载资源的url地址
data:可选,传递给url的参数
callback:可选,回调函数,在请求完成时调用(请求成功,失败都会调用),函数参数:
responseText:返回结果
statusText:返回状态
xmlHttprequest:http请求对象
********************
示例:加载静态页面
test.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:align="center">
hello world <br>
<strong>好漂亮啊<br></strong>
</div>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/jquery/jquery-3.5.1.min.js"></script>
</head>
<script>
$(function () {
$("#btn").click(function () {
$("#span").load("/html/test.html");
});
$("#btn2").click(function () {
$("#span2").load("/html/test.html strong");
})
})
</script>
<body>
<div th:align="center">
<span id="span"></span><br>
<span id="span2"></span>
<button id="btn">加载文档</button>
<button id="btn2">加载文档2</button>
</div>
</body>
</html>
说明:btn加载文档全部内容,btn2加载文档指定内容
点击btn、btn2
********************
示例:加载后端服务数据
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello 瓜田李下";
}
@RequestMapping("/hello2")
public String hello2(String name){
return "hello "+name;
}
@RequestMapping("/hello3")
public Map<String,String> hello3(String name){
Map<String,String> map=new HashMap<>();
map.put("info",name);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/jquery/jquery-3.5.1.min.js"></script>
</head>
<script>
$(function () {
$("#btn").click(function () {
$("#span").load("/hello");
});
$("#btn2").click(function () {
$("#span2").load("/hello2",{name: "瓜田李下"},function (result,status) {
alert(result+" "+status);
})
});
$("#btn3").click(function () {
$("#span3").load("/hello3",{name: "海贼王"},function (result) {
alert(result);
})
})
})
</script>
<body>
<div th:align="center">
<span id="span"></span><br>
<span id="span2"></span><br>
<span id="span3"></span><br>
<button id="btn">加载文档</button>
<button id="btn2">加载文档2</button>
<button id="btn3">加载文档3</button>
</div>
</body>
</html>
点击btn、btn2、btn3
btn3回调函数result.info,输出:undifined,直接使用result