使用Ajax对表单的提交(返回json格式SSM)
我们先来简单的了解下什么是ajax,以及它的一些用出
1.什么是ajax?
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)
ajax实现了异步请求,我们可以不需要刷新页面,就可以通过ajax请求获取数据,一般的校验都会用到ajax,比如,注册的时候判断用户名是否存在等等用ajax能够更加的快捷、方便
2.使用ajax对表单的提交
前台请求代码
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "login.action" ,//url
data: $('#form1').serialize(),
success: function (data) {
console.log(data);//打印服务端返回的数据(调试用)
if (data.code ==200) {
alert("登录成功!");
}else{
alert("登陆失败!"+data.Msg);
}
;
}
});
}
</script>
</head>
<body>
<form id ="form1" action="" method="post" onsubmit="return false">
用户名<input type="text" name="uname" ><br/>
密码<input type="password" name="upassword"><br/>
<input type="submit" onclick="login();" value="登陆">
</form>
后端controller层接收代码
//验证登录
@RequestMapping(value="/login",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
@ResponseBody
public void login(User user,HttpServletResponse response) throws IOException{
JSONObject json=new JSONObject();
if (user.getUpassword().equals("123")) {
json.put("code", 200);
json.put("Msg", "验证成功!");
}else {
json.put("code", 400);
json.put("Msg", "密码错误");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(json.toJSONString());
}
效果展示块
在这过程中我也遇到了多种错误,请求406错误,返回结果Msg乱码错误等等,如果你在这个过程中也遇到了这些错误,可以一起探讨一下