Ajax to do a simple login authentication

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_45660111/article/details/102741586

ajax interact with the server can be done in the case of the page does not refresh!

Code shows:
1.juqery Code:

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src= "js/jquery1.js"></script>
	</head>
	
	<body>
		姓名:<input type="text" name = "name" id="name" /><br />
		密码:<input type="text" name = "pwd"  id="pwd"/><br />
		<input type="button" value="登录" />
		<div id = "show"></div>
		<script>
			$(function(){
				$(function(){
					$(":button").on("click",function(){
						$.ajax({
							url:"logIn",
							type:"post",
							data:{
								name:$("#name").val(),
								pwd:$("#pwd").val()
							},
							dataType:"text",
							success:function(data){
								if(data == "ok"){
									window.location.href = "test.jsp";
								}else{
									$("#show").text("登录失败!");
								}
							}
						})
					})
				});
			});
		</script>
	</body>
</html>

2.servlet Code:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String name = "admin";
		String pwd = "123456";

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String ajaxName = request.getParameter("name");
		String ajaxPwd = request.getParameter("pwd");
		
		if(name.equals(ajaxName)&&pwd.equals(ajaxPwd)){
			out.print("ok");
		}else{
			out.print("error");
		}
		out.flush();
		out.close();
	}

Guess you like

Origin blog.csdn.net/qq_45660111/article/details/102741586