在采用JQuery进行表单异步提交时,前台传入的是json数据格式,后台controller用map接收,再传回前台进行结果判断时,if-else接收结果()里面,尽量不要出现“=”,不然判断语句失效,应该在后台将一个boolean类型的flag变量存入map中:map.put("flag",true/false); 前台if(result.flag)进行判断。
前台:提交表单
$("#form1").on("click",".btn",function(e){
var userName =$('#userName').val();
var password =$('#password').val();
$.ajax({
type:'POST',
data: {userName:userName,password:password},
url:'/register',
dataType:'json',
success:function(result){
if (result.flag){//注册成功
alert(result.msg);
window.location.href="/goLogin";
} else {//注册失败
alert(result.msg);
window.location.href="${root}/goRegister";
}
}
});
}
后台:
@RequestMapping(value="/register" , method= RequestMethod.POST , produces="application/json;charset=UTF-8")
public @ResponseBody Map userReg(@RequestParam("userName") String userName, @RequestParam("password") String password,HttpServletResponse response){
Map<String,Object> map = new HashMap<String, Object>();
boolean flag=false;
if(userName!=null && !"".equals(userName) && password!=null && !"".equals(password)) {
String name=userName;//给name赋值
User user1=userService.selectUserName(userName,name);
System.out.println(user1);
String identity=password;//给identity赋值
User user2=userService.selectPassword(password,identity);
System.out.println(user2);
if(user1 == null && user2 == null) {
flag=true;
map.put("flag", flag);
map.put("msg", "注册成功!");
System.out.println("123");
return map;
}
}
map.put("flag", flag);
map.put("msg", "注册失败!");
System.out.println("456");
return map;
}