php如何使用AJax和json实现登录验证

php用AJax和json实现登录验证的方法是:1、创建一个jsp示例文件,导入jquery依赖和fastjson依赖文件;2、新建login.js文件,获取用户名和密码文本内容;3、新建controller类,查询用户是否存在并把对象转化为json字符串类型返回给js文件;4、js判断是否成功然后进行页面跳转即可。

本教程操作系统:Windows10系统、php8.1.3版本、Dell G3电脑。

AJAX和Json完成用户登录

1、提前导入jquery依赖和fastjson依赖

2、新建jsp页面

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<%@ 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、新建js文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

$(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、新建controller类

查询是否存在此用户

把map对象转换成json字符串类型,写入到内存,并返回给js文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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));

}

登录后复制

以上就是php如何使用AJax和json实现登录验证的详细内容,更多请关注php中文网其它相关文章!

TG交流群(点击进入)----付费帮助搭建---修复---二开,以及发布求资源.
QQ交流群 922260178
© 版权声明
THE END
喜欢就支持一下吧
点赞1.4W+ 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容