我们先不讲ajax的原理,还是先以实战为主,看一下这个东西到底怎么用的?
form表单:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div style="width: 300px; padding: 20px; margin: 20px; border: 4px dashed #ccc;"> <form id="myform" name="myform" method="post" action="#"> <table> <tr> <td>用户名:</td> <td><input type="text" id="username" name="username" placeholder="请输入用户名" onfocus="this.placeholder=''" onblur="this.placeholder='请输入用户名'" /></td> </tr> <tr> <td>密码:</td> <td><input type="password" id="password" name="password" placeholder="请输入密码" onfocus="this.placeholder=''" onblur="this.placeholder='请输入密码'" /></td> </tr> <tr> <td colspan="2"><input type="button" value="提交" onclick="doLogin('weixin');" /></td> </tr> </table> <input type="hidden" name="loginType" id="loginType" value="weixin" /> </form> </div> <div id="errMsg" style="color: red">${errMsg}</div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> function doLogin(type) { $.ajax({ type : "GET", url : "login.do", data : { username : $("#username").val(), password : $("#password").val(), type : type }, dataType : "json", //预期服务器返回的数据 success : function(data) { if (data.errCode < 0) { alert("登录失败!") $("#errMsg").show().html(data.errMsg).stop(true, true) .fadeOut(3000); } else { //登录成功,做其他处理 alert("恭喜你,登录成功!"); } } }); } </script> </body> </html>
LoginServlet
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("用户登录..."); System.out.println("开始存入map..."); Map<String,Object> map=StringUtils.getParameters(req); System.out.println("存入map成功!"); System.out.println(map); if(StringUtils.isEmpty(map.get("username"))){ StringUtils.writeObject(resp, "{\"errCode\":-1,\"errMsg\":\"用户名不能为空!\"}"); System.out.println("用户名不能为空!"); return; } if(StringUtils.isEmpty(map.get("password"))){ StringUtils.writeObject(resp,"{\"errCode\":-2,\"errMsg\":\"密码不能为空!\"}"); System.out.println("密码不能为空!"); return; } System.out.println("登陆成功!"); StringUtils.writeObject(resp,"{\"errCode\":0,\"errMsg\":\"登录成功!\"}"); }
页面效果:
参考:https://www.cnblogs.com/skyblue-li/p/8251234.html