php uses AJax and json to implement login verification: 1. Create a jsp sample file and import jquery dependency and fastjson dependency files; 2. Create a new login.js file to obtain the user name and password text content; 3. , create a new controller class, query whether the user exists and convert the object into a json string type and return it to the js file; 4. js determines whether it is successful and then jumps to the page.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
AJAX and Json complete user login
1. Import jquery dependencies and fastjson dependencies in advance
2. Create a new jsp page
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-3.4.1.js"></script> <script type="text/javascript" src="login.js"></script> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- 不使用submit,用ajax+json实现局部刷新,实现登录 --> <form action="" method="post"> <span id="msg"></span><br/> 用户姓名:<input type="text" name="username" id="username"><br/> 用户密码:<input type="text" name="password" id="password"><br/> <input type="button" value="登录" id="submit"> </form> </body> </html>
3. Create a new js file
$(function(){ $("#submit").click(function(){ var username = $("#username").val(); var password = $("#password").val(); //获取json格式的文本内容 $.post("login?mark=login",{"username":username,"password":password}, function(data){ if(data.log){ /*输入要跳转的页面*/ /*window.location.href="https://www.php.cn/link/3729ff995bfa947622cdf0612e57c332";*/ alert("success"); }else{ $("#msg").css("color","red").html(data.msg); } },"json" ); }); });
4. Create a new controller class
Query whether This user exists
Convert the map object into a json string type, write it to the memory, and return it to the js file
private void login(HttpServletRequest request, HttpServletResponse response) throws Exception { // response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); String msg = ""; String username = request.getParameter("username"); String password = request.getParameter("password"); Map<String, Object> map = new HashMap(); //查询是否存在此用户 User user = new LoginServer().login(username, password); if(user!=null) { map.put("log", true); map.put("msg", "成功"); }else { map.put("log", false); map.put("msg", "用户名或者密码错误"); } //把map对象转换成json字符串类型,写入到内存,并返回给js文件 writer.write(JSON.toJSONString(map)); }
The above is the detailed content of How to use AJax and json to implement login verification in php. For more information, please follow other related articles on the PHP Chinese website!