校验用户名是否存在案例
1.服务器响应的数据,在客户端使用时,要想当做json数据格式使用
1.$.get(type):将最后一个参数type指定为"json"
2.在服务器端设置MIME类型
response.setContentType("application/json;charset=utf-8");
FindUserServlet:
@WebServlet("/findUserServlet") public class FindUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户名 String username = request.getParameter("username"); //调用service层判断用户名是否存在 response.setContentType("text/html;charset=utf-8"); //response.setContentType("application/json;charset=utf-8"); Map<String, Object> map = new HashMap<String, Object>(); if ("tom".equals(username)){ //存在 map.put("userExsit",true); map.put("msg","此用户名存在,请换一个"); }else { //不存在 map.put("userExsit",false); map.put("msg","用户名可以使用"); } //将map转为json,并且传递给客户端 ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(),map); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
5-regist.html:页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //在页面加载完成后 $(function () { //给username绑定blur事件 $("#username").blur(function () { //获取username文本输入框的值 var username = $(this).val(); //发送ajax请求 //期望服务器响应的数据格式:{"userExsit":true,"msg":"此用户名存在,请换一个"} // {"userExsit":false,"msg":"用户名可以使用"} $.get("findUserServlet",{username:username},function (data) { //判断userExsit键的值是否存在true var span = $("#s_username"); if (data.userExsit){ //用户名存在 span.css("color","red"); span.html(data.msg); }else { //用户名不存在 span.css("color","green"); span.html(data.msg); } },"json"); }); }); </script> </head> <body> <form> <input type="text" id="username" name="username" placeholder="请输入用户名"> <span id="s_username"></span> <br> <input type="password" name="password" placeholder="请输入密码"><br> <input type="submit" value="注册"><br> </form> </body> </html>
搜索
复制
标签:username,map,用户名,校验,案例,json,msg,response From: https://www.cnblogs.com/pengtianyang/p/16609613.html