Ajax实现登录案例
ajax登录案例,供大家参考,具体内容如下
msg
package com.lbl.msg; public class msg { string msg; int code; public msg() { } public msg(string msg, int code) { this.msg = msg; this.code = code; } public string getmsg() { return msg; } public void setmsg(string msg) { this.msg = msg; } public int getcode() { return code; } public void setcode(int code) { this.code = code; } }
registerservlet
package com.lbl.servlet; import com.fasterxml.jackson.databind.objectmapper; import com.lbl.msg.msg; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; @webservlet("/register") public class registerservlet extends httpservlet { protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //1:获取请求发送的数据 string username = request.getparameter("username"); response.setcontenttype("text/html;charset=utf-8"); //2:判断用户名是否注册 if("abc123".equals(username)){ msg msg = new msg("用户名已经注册",0); //用户名已经注册 {"flag":false,"info":"用户名已经注册"}; // string jsonstr = "{\"flag\":false,\"info\":\"用户名已经注册\"}"; //响应回浏览器 response.getwriter().write(new objectmapper().writevalueasstring(msg)); }else{ msg msg = new msg("可以注册",1); //用户名没有注册 // string jsonstr = "{\"flag\":true,\"info\":\"可以注册\"}"; //响应回浏览器 response.getwriter().write(new objectmapper().writevalueasstring(msg)); } } }
json_register.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <script src="js/jquery-3.3.1.js"></script> <script type="application/javascript"> $(function () { //1: 给用户名输入框绑定失去焦点事件(onfocus onblur) $("#username").on("blur",function () { //获取用户名输入框数据 var username = $("#username").val(); //2:向服务器发出异步请求,让服务器去查询用户名是否存在 $.post( "register", //表示服务器的servlet路径 "username="+username, //表示向服务器发送的数据 function (data) { // msg:用户名已经注册 code:0 if(data.code==0){ // alert(data.info); $("#spanid").html(data.msg).css("color","green"); }else { $("#spanid").html(data.msg).css("color","red"); } }, "json" ); }); }); </script> </head> <body> <div> <font>会员注册</font>user register <form class="form-horizontal" style="margin-top: 5px;"> <table> <tr> <td>用户名</td> <td> <input type="text" id="username" name="username" placeholder="请输入用户名"> <span id="spanid"> </td> </tr> <tr> <td>密码</td> <td> <input type="password" placeholder="请输入密码"> </td> </tr> </table> <input type="submit" value="注册"/> </form> </div> </body> </html>
运行效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。