Ajax用户登录

后台

@Controller
public class AjaxController {	
//用户登录
	@RequestMapping("/login")
	@ResponseBody
	public Boolean login(String username,String password){
		System.out.println(username);
		System.out.println(password);
		if("admin".equals(username) && "123".equals(password)){
			return true;//登录成功
		}
		return false;
	}
}

 

两个前台页面:

1.登录成功后的页面:index.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	恭喜你,登录成功!!!!!1
</body>
</html>

2.登录页面:login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//返回Ajax对象 
	function getAjax() {
		if (XMLHttpRequest) {
			return new XMLHttpRequest();
		} else {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	function login() {
		//解决前台传值到后台为空
		var username = document.getElementById("username").value;
		var password = document.getElementById("password").value;
		
		//1.拿到Ajax对象
		var xhr = getAjax();
		//2.open:准备URL【解决参数传值问题】
		xhr.open("post","/login");
		//修改请求头(POST请求传参,必需加这一句,而且它的位置在open后面,send前面)
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		//3.监听对象状态变化,拿到返回数据
		xhr.onreadystatechange = function(){
			if(xhr.readyState==4&& xhr.status==200){
				var result = xhr.responseText;//返回的是一个字符串 "true","false"
				console.debug(result);
				if(result == "true"){
					window.location.href ="/index.jsp";//登录成功跳转到index页面
				}else{
					document.getElementById("erroLogin").innerHTML="用户名或密码错误,登录失败";
				}
			}
		}
		//4.发送请求
		//如果是POST请求,在send方法中发送数据
		xhr.send("username="+username+"&password="+password)
	}
</script>
</head>
<body>
	<form action="/checkName" method="post">
		用户名:<input type="text" name="username" id="username"/><br/>
		密码:<input type="password" name="password" id="password"/><br/>
		<input type="button" onclick="login();" value="登录">
		<span id="erroLogin"></span>
	</form>
</body>
</html>

===》效果展示图

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值