一、前端发送ajax请求
- 前端jquery代码
$.ajax({
url :'ajaxLogin',
data :$("#userForm").serialize(),
type :'post',
success : function(data) {
var m=jQuery.parseJSON(data);
if(m.message == "true"){
window.location.href="index";
}else {
alert("用户名或者密码错误!")
}
},
error : function() {
alert("ajaxLogin登入失败!");
}
});
- 后端接收Ajax请求
@RequestMapping(value="/ajaxLogin",method=RequestMethod.POST)
public void ajaxLogin(@Validated User user,BindingResult bindingResult,HttpServletResponse response) throws IOException{
if(bindingResult.hasErrors()){
List<ObjectError> errorList = bindingResult.getAllErrors();
for(ObjectError error:errorList){
System.out.println(error.getDefaultMessage());
}
}
boolean isLogin=loginService.isLogin(user.getUsername(), user.getPassword());
JSONObject jsonObject = new JSONObject();
String message = "";
if(isLogin){
message = "true";
}else
message = "false";
jsonObject.put("message", message);
response.getWriter().write(jsonObject.toString());
}
注意事项
- 当Ajax请求的contentType属性指定为’application/json;charset=utf-8’时,请求的是json数据。
- data属性的值必须为json数据。如data:’{“name”:”张三”}’,。
- 在后台用pojo实体类接收数据时,在参数前面要加上@RequestBody注解,将json数据注入实体对象中。
- 当Ajax请求的contentType属性没有指定时,默认值为contentType = “application/x-www-form-urlencoded”。
- data属性的值必须为key/value类型的数据
- 后台接收用实体类接收也不需要加上注解。