@[toc]
Ajax 学习总结
一、Ajax包的导入
二、Ajax的异步请求
在使用时要引用
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
后台添加的数据
@RequestMapping("/a2")
public List<User> a2(){
List<User> listuser=new ArrayList<User>();
//添加数据
listuser.add(new User("小明1",12,"男"));
listuser.add(new User("小明2",13,"男"));
listuser.add(new User("小明3",14,"男"));
listuser.add(new User("小明4",18,"男"));
return listuser;
}
前端拿到数据
<script>
$(function () {
$("#btn").click(function () {
$.post({
url:"${pageContext.request.contextPath}/a2",
success:function (data) {
//console.log(data);
let html="";
for (let i=0;i<data.length;i++){
html +="<tr>"+
"<td>"+data[i].name+"</td>"+
"<td>"+data[i].age+"</td>"+
"<td>"+data[i].sex+"</td>"+
"</tr>"
}
$("#context").html(html)
}
})
})
})
</script>
注意点:
url:为前端请求后端数据接口
data:前端传入到后端的值,可以省略
succcess:数据请求成功后从后端拿到数据
数据的拼接:html +="<tr>"+
"<td>"+data[i].name+"</td>"+
"<td>"+data[i].age+"</td>"+
"<td>"+data[i].sex+"</td>"+
"</tr>"
三、Ajax 表单验证
Json乱码问题解决
<!--Json乱码问题解决-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
表单获取后端的数据
function a1() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{
"name":$("#name").val()},
success:function (data) {
if (data.toString()=='ok'){
$("#userInfo").css("color","green");
}else {
$("#userInfo").css("color","red");
}
$("#userInfo").html(data);
}
})
}
表单校验
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
<script>
function a1() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{
"name":$("#name").val()},
success:function (data) {
if (data.toString()=='ok'){
$("#userInfo").css("color","green");
}else {
$("#userInfo").css("color","red");
}
$("#userInfo").html(data);
}
})
}
function a2() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{
"pwd":$("#pwd").val()},
success:function (data) {
if (data.toString()=='ok'){
$("#pwdInfo").css("color","green");
}else {
$("#pwdInfo").css("color","red");
}
$("#pwdInfo").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
<%--onblur失去焦点事件--%>
</p>
<p>
密码:<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
<%--onblur失去焦点事件--%>
</p>
</body>
</html>
好了,今天的分享就到这里了哦