今天学会了使用ajax实现异步加载数据(页面不刷新获得后台数据)
首先需要导入JSON需要的依赖
<!-- JSON-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
下载并且导入jquery包
注意乱码问题以及版本兼容性问题
解决乱码问题
将
<!-- 添加注解驱动-->
<mvc:annotation-driven>
替换为
<!-- 添加注解驱动-->
<!-- 处理请求返回json字符串的乱码问题(jackson) -->
<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>
测试
controller
package com.zyy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class TestController {
@RequestMapping("/test")
public String enterAjax(){
return "ajaxTest";
}
@RequestMapping("/ajax")
@ResponseBody
public String callback(String userName,String passWord){
String msg="";
if(userName!=null){
if ("zyy".equals(userName)){
msg = "ok";
}
else {
msg = "用户名不存在";
}
}
if(passWord!=null){
if ("123456".equals(passWord)){
msg = "ok";
}
else {
msg = "密码错误";
}
}
System.out.println("msg="+msg);
return msg;
}
}
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/ajax",
data:{"userName":$("#userName").val()},
success:function (data){
if(data.toString()==="ok"){
$("#userNameMsg").css("color","green");
}else {
$("#userNameMsg").css("color","red ");
}
$("#userNameMsg").html(data);
}
})
}
function b(){
$.post({
url:"${pageContext.request.contextPath}/ajax",
data:{"passWord":$("#passWord").val()},
success:function (data){
if(data.toString()==="ok"){
$("#passWordMsg").css("color","green");
}else {
$("#passWordMsg").css("color","red");
}
$("#passWordMsg").html(data);
}
})
}
</script>
</head>
<body>
<input type="text" id="userName" onblur="a()">
<span id="userNameMsg"></span>
<input type="password" id="passWord" onblur="b()">
<span id="passWordMsg"></span>
</body>
</html>