摘要:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户登录验证</title>
</head>
<body>
<div style="width: 300px; height: 300px; margin: 50px;border: 1px solid #ccc;background: #ccc;border-radius: 5px; ">
<h2 style="text-align: center;">用户登录</h2>
<form action="" method="post" style="text-align: center;">
<p>邮箱:<input type="email" name="email" value=""></p>
<p>密码:<input type="password" name="password"></p>
<p><button>登录</button></p>
</form>
<script>
let btn = document.getElementsByTagName('button')[0];
btn.onclick = function(){
//1.创建xhr对象
let xhr = new XMLHttpRequest();
//2.监听响应状态
xhr.onreadystatechange = function(){
if (xhr.readyState===4){ //状态就绪
//判断是否获取到响应的数据
if(xhr.status===200){
//在页面中创建一个新元素用来显示响应的数据
let p = document.createElement('p');
p.style.color = 'red';
//将服务器端返回的JSON字符串转为JS对象
let json = JSON.parse(xhr.responseText);//xhr.responseText是从服务器上取回的数据
//如果json.status == 1,表示查询成功
if (json.status == 1){
p.innerHTML = json.msg;
}else if(json.status == 0){
p.innerHTML = json.msg;
}
//将新元素插入到当前页面中
document.forms[0].appendChild(p);
btn.disabled = true; //禁用按钮
setTimeout(function(){
document.forms[0].removeChild(p);
btn.disabled = false; //启用按钮
//如果登录成功就跳转到网站的入口
if(json.status == 1){
location.href = 'admin.php'
}
},2000);
} else {
alert('响应失败'.xht.status);
}
} else {
}
}
//3.设置请求参数
xhr.open('post','inc/check.php',true);
//4.设置头信息,将内容类型设置为表单提交方式
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//5.发送请求
let data = {
email: document.getElementsByName('email')[0].value,
password: document.getElementsByName('password')[0].value,
};
let data_json = JSON.stringify(data); //将JS对象转为JSON字符串
xhr.send('data=' + data_json);
btn.disabled = true; //禁用按钮
}
</script>
</div>
</body>
</html>
批改老师:天蓬老师批改时间:2019-05-27 13:14:44
老师总结:其实一个登录验证, 可以考验出一个程序员多方面的技能 , 是一种非常经典的面试题
