abstract:<!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>用戶登錄驗(yàn)證</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.創(chuàng)建xhr對(duì)象
let xhr = new XMLHttpRequest();
//2.監(jiān)聽響應(yīng)狀態(tài)
xhr.onreadystatechange = function(){
if (xhr.readyState===4){ //狀態(tài)就緒
//判斷是否獲取到響應(yīng)的數(shù)據(jù)
if(xhr.status===200){
//在頁面中創(chuàng)建一個(gè)新元素用來顯示響應(yīng)的數(shù)據(jù)
let p = document.createElement('p');
p.style.color = 'red';
//將服務(wù)器端返回的JSON字符串轉(zhuǎn)為JS對(duì)象
let json = JSON.parse(xhr.responseText);//xhr.responseText是從服務(wù)器上取回的數(shù)據(jù)
//如果json.status == 1,表示查詢成功
if (json.status == 1){
p.innerHTML = json.msg;
}else if(json.status == 0){
p.innerHTML = json.msg;
}
//將新元素插入到當(dāng)前頁面中
document.forms[0].appendChild(p);
btn.disabled = true; //禁用按鈕
setTimeout(function(){
document.forms[0].removeChild(p);
btn.disabled = false; //啟用按鈕
//如果登錄成功就跳轉(zhuǎn)到網(wǎng)站的入口
if(json.status == 1){
location.href = 'admin.php'
}
},2000);
} else {
alert('響應(yīng)失敗'.xht.status);
}
} else {
}
}
//3.設(shè)置請(qǐng)求參數(shù)
xhr.open('post','inc/check.php',true);
//4.設(shè)置頭信息,將內(nèi)容類型設(shè)置為表單提交方式
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//5.發(fā)送請(qǐng)求
let data = {
email: document.getElementsByName('email')[0].value,
password: document.getElementsByName('password')[0].value,
};
let data_json = JSON.stringify(data); //將JS對(duì)象轉(zhuǎn)為JSON字符串
xhr.send('data=' + data_json);
btn.disabled = true; //禁用按鈕
}
</script>
</div>
</body>
</html>
Correcting teacher:天蓬老師Correction time:2019-05-27 13:14:44
Teacher's summary:其實(shí)一個(gè)登錄驗(yàn)證, 可以考驗(yàn)出一個(gè)程序員多方面的技能 , 是一種非常經(jīng)典的面試題