abstrak:index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> </head> <body> <h3>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> </head> <body> <h3>用戶登錄</h3> <form action=""> <p>郵箱:<input type="email" name="email"></input></p> <p>密碼:<input type="password" name="password"></input></p> <p> <button type="button">登錄</button> </p> </form> <script> let btn = document.getElementsByTagName("button")[0]; btn.onclick = function(){ //1. 創(chuàng)建xhr對象 let xhr = new XMLHttpRequest(); //2. 監(jiān)聽響應(yīng)狀態(tài) xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ //判斷是否拿到了響應(yīng)數(shù)據(jù) if(xhr.status === 200){ let p = document.createElement('p'); p.style.color = 'red'; //將服務(wù)器端返回的json字符串轉(zhuǎn)為js對象 let json = JSON.parse(xhr.responseText); console.log(json); p.innerHTML = json.msg; document.forms[0].appendChild(p); //禁用按鈕,防止重復(fù)點擊 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)失敗", xhr.status); } } else { //http請求正在繼續(xù),這里可以放一個gif圖 } } //3. 設(shè)置請求參數(shù) xhr.open('post', "check.php", true); //4. 設(shè)置請求頭,將內(nèi)容類型設(shè)置為表單提交方式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //5. 發(fā)送請求 let data = { email : document.getElementsByName('email')[0].value, password : document.getElementsByName('password')[0].value } //將js對象轉(zhuǎn)換為json字符串 let data_json = JSON.stringify(data); xhr.send('data='+data_json); } </script> </body> </html>
check.php
<?php //登陸驗證 // print_r($_POST) ; $user = json_decode($_POST['data']); $email = $user->email; $password = $user->password; $pdo = new PDO('mysql:host=localhost; dbname=php', 'wjh', '1010'); $sql = "SELECT count(*) FROM `user` WHERE `email`='{$email}' AND `password`='{$password}'"; $stmt = $pdo->prepare($sql); $stmt->execute(); if($stmt->fetchColumn(0) == 1){ echo json_encode(['status'=>1, 'msg'=>'登錄成功,正在跳轉(zhuǎn)...']); exit; } else { echo json_encode(['status'=>0, 'msg'=>'登錄失敗,郵箱或密碼錯誤...']); exit; }
admin.php
<?php echo "<h2>WELCOME</h2>";
Guru membetulkan:天蓬老師Masa pembetulan:2019-05-13 09:45:13
Rumusan guru:異步驗證技術(shù) , 是每一個web開發(fā)人員必須掌握的基本技能, 你的流程是正確 的...