您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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" > <table> <tr> <td>用戶名</td> <td> <input type="text" id="username" name="username" placeholder="請輸入用戶名"> <span id="spanId"></span> </td> </tr> <tr> <td>密碼</td> <td> <input type="password" placeholder="請輸入密碼"> </td> </tr> </table> <input type="submit" value="注冊"/> </form> </div> </body> </html>
運行效果:
感謝各位的閱讀!關于“Ajax實現登錄的方法”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。