Ajax+jquery实现异步验证用户名功能
生活随笔
收集整理的這篇文章主要介紹了
Ajax+jquery实现异步验证用户名功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>登錄</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><!-- 引入 Bootstrap --><link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"><script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script> </head> <body> <script>function checkUser() {$.post({url:"${pageContext.request.contextPath}/user/registerAjaxCheck",data: {'name':$('#username').val()},success:function (data) {if (data.toString()==='OK'){$('#info').css("color","blue");$('#info').html("用戶名可以注冊");}else if (data.toString()==='null'){$('#info').css("color","red");$('#info').html("用戶名不能為空");} else {$('#info').css("color","red");$('#info').html("用戶名已存在");}}});} </script> <form action="${pageContext.request.contextPath}/user/insertUser" method="post" class="form-horizontal"><div style="height: 20%"></div><div style="width: 80%;align-content: center" ><div style="width: 100%;align-content: center;height: 30px;"><span id="info" style="margin-left: 20%">${msg2}</span></div><div class="form-group" ><label class="col-sm-2 control-label">用戶名</label><div class="col-sm-10"><input onblur="checkUser()"id="username"style="width: 30%" type="text" class="form-control" placeholder="輸入用戶名" name="userName"></div></div><div style="width: 100%;align-content: center;height: 30px;"></div><div class="form-group"><label class="col-sm-2 control-label">密碼</label><div class="col-sm-10"><input style="width: 30%"type="password" class="form-control" placeholder="輸入密碼" name="password"></div></div><div class="form-group" ><div class="col-sm-offset-2 col-sm-10" ><button type="submit" class="btn btn-default">注冊</button></div></div></div> </form> </body> </html>Controller
注意返回的是一個json字符串,ajax是前后端分離的核心。
//Ajax異步驗證用戶名@RequestMapping("/registerAjaxCheck")@ResponseBodypublic String registerAjaxCheck(String name , HttpServletResponse response){System.out.println(name);User user = userService.checkUser(name);String msg = "";if (name==null||name.equals("")){msg = "null";}else if (user==null){msg = "OK";}System.out.println(msg);return msg;}總結
以上是生活随笔為你收集整理的Ajax+jquery实现异步验证用户名功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SSM框架中分页插件pageHelper
- 下一篇: 自定义LocaleResolver实现页