请求是json格式,那么springmvc返回的格式也必须是json
不然会出现,返回错误,执行error函数
首先要用到 json 的jar包
<!--json转对象-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
发送请求
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
document.getElementById("submit").onclick=function(){
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
alert("ks");
$.ajax({
url:"user/equale", //请求地址
contentType:"application/json;charset=UTF-8", //传输数据类型
data:JSON.stringify({name:name,password: password}), //要传输的数据
dataType:"json", //返回值类型
type:"post", //请求方式
success:function(msg){ //data表示服务端响应的数据
//在此处读取返回的msg数据
},
complete : function(xhr, status) {
//拦截器实现超时跳转到登录页面
}
});
}
</script>
https://blog.csdn.net/wangzhiguo9261/article/details/80893244
接收请求,将返回信息转换成 json 并返回 json
//对比一个用户(用户名密码)
@RequestMapping(value = "/equale" ,method = RequestMethod.POST)
public @ResponseBody String equaleUser(@RequestBody Users user) throws JsonProcessingException {
System.out.println("对比一个用户(用户名密码)");
System.out.println(user+" * * * *user");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString("success");
return str;
}