7,Ajax技术
文章目录
简介
- AJAX = Asynchronous JavaScript and XML (异 JavaScript 和XML) .
- AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
- Ajax不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
就如同百度搜索, 不需要刷新页面
- 传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
- 使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
- 使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。
7.1jQuery.ajax
- 纯JS原生实现Ajax可以去了解下JS原生XMLHttpRequest!
- Ajax的核心是XMLHttpRequest对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。
- jQuery提供多个与AJAX 有关的方法。
- 通过jQuery AJAX 方法,您能够使用HTTP Get 和HTTP Post从远程服务器上请求文本、HTML,XML或JSON -同时您能够把这些外部数据直接载入网页的被选元素中。
- jQuery 不是生产者,而是大自然搬运工。
- jQuery Ajax本质就是 XMLHttpRequest,对他进行了封装,方便调用!
jQuery.ajax(...)
部分参数:
url:请求地址
type:请求方式,GET、POST(1.9.0之后用method)
headers:请求头
data:要发送的数据
contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否异步
timeout:设置请求超时时间(毫秒)
beforeSend:发送请求前执行的函数(全局)
complete:完成之后执行的回调函数(全局)
success:成功之后执行的回调函数(全局)
error:失败之后执行的回调函数(全局)
accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
dataType:将服务器端返回的数据转换成指定类型
"xml": 将服务器端返回的内容转换成xml格式
"text": 将服务器端返回的内容转换成普通文本格式
"html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
"script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
"json": 将服务器端返回的内容转换成相应的JavaScript对象
"jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
jquery官网下载
7.2,Ajax-简单测试
1、配置web.xml 和 springmvc的配置文件,复制上面案例的即可
2、UserController中添加一个方法
@Controller
//@RequestMapping("/user")
@RestController//不使用视图解析器
public class UserController {
@Autowired
public UserService service;
@RequestMapping("/a1")
public void a1(String userCode, String userPwd,HttpServletResponse response) throws IOException {
System.out.println("userCode----"+userCode);
System.out.println("userPwd----"+userPwd);
if ("zs".equals(userCode)) {
response.getWriter().println("true");
}else {
response.getWriter().println("false");
}
}
}
3、导入jquery , 可以使用在线的CDN , 也可以下载导入
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
4、编写ajax.jsp测试
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/user/a1",
data:{"userCode":$("#userCode").val(),"userPwd":$("#userPwd").val()},
success: function (data){
alert(data);
}
})
}
</script>
</head>
<body>
<%--失去焦点的时候, 发起一个请求,携带信息到后台--%>
用户名:<input type="text" id="userCode" onblur="a()">
密码:<input type="text" id="userPwd" onblur="">
</body>
</html>
5、测试
7.3,Ajax-传递一个对象试试
1,导包JSON
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
2,在BooksController中添加一个b1,返回list
@Controller
//@RequestMapping("/user")
@RestController //不使用视图解析器
public class UserController {
@Autowired
public UserService service;
@RequestMapping("/b1")
public List<Books> b1() throws IOException {
List<Books> list = new ArrayList<>();
list = service.queryBooks(null, 0);
return list;
}
}
3,前端页面ajax2.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script>
$(function (){
$("#btn").click(function (){
$.post("${pageContext.request.contextPath}/b1",function (data){
console.log(data);
let html = "";
for (let i = 0; i < data.length ; i++){
html += "<tr>"+
"<td>"+data[i].bookID+"</td>"+
"<td>"+data[i].bookName+"</td>"+
"<td>"+data[i].bookCounts+"</td>"+
"<td>"+data[i].detail+"</td>"+
"</tr>"
}
$("#content").html(html);
});
})
});
</script>
</head>
<body>
<input type="submit" value="显示数据" id="btn">
<table class="table table-hover table-striped">
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
<tbody id="content">
</tbody>
</table>
</body>
</html>
4,测试
7.4,Ajax-实现验证用户名密码
UserController
@Controller
//@RequestMapping("/user")
@RestController //不使用视图解析器
public class UserController {
@Autowired
public UserService service;
@RequestMapping("/login")
public Map<String, String> login1(String userCode, String userPwd, HttpServletResponse response) throws IOException {
int i = service.queryUserCount(userCode);//根据用户名获取count(1)
Map<String, String> map = new HashMap<>();
//查不到数据说明用户名错了
if (i == 1) {//只有1条说明用户名正确
map.put("codeMsg","用户名ok");
User user = service.login(userCode, userPwd);//根据用户名密码查询user
if (user!=null){//查询到用户说明密码正确
map.put("pwdMsg","密码ok");
}else {
map.put("pwdMsg","密码错误");
}
}else {
map.put("codeMsg","用户名错误");
map.put("pwdMsg","用户名错误无法验证密码");
}
return map;
}
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/login",
data:{"userCode":$("#code").val(),"userPwd":$("#pwd").val()},
success: function (data){
console.log(data);
if (data.codeMsg ==='用户名ok'){
$("#codeMsg").css("color","green");
}else if (data.codeMsg ==='用户名错误'){
$("#codeMsg").css("color","red");
}
if (data.pwdMsg ==='密码ok'){
$("#pwdMsg").css("color","green");
} else {
$("#pwdMsg").css("color","red");
}
$("#codeMsg").html(data.codeMsg);
$("#pwdMsg").html(data.pwdMsg);
}
})
}
</script>
</head>
<body>
<p>
用户名: <input type="text" id="code" οnblur="a1()">
<span id="codeMsg"></span>
</p>
<p>
密码: <input type="text" id="pwd" οnblur="a1()">
<span id="pwdMsg"></span>
</p>
</body>
</html>