摘要:<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <ti
<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>Login</title> <style> * { padding: 0; margin: 0; } .box { margin: 20px auto; width: 260px; text-align: center; } form { margin: 20px auto; overflow: hidden; } form p { margin: 10px 0; height: 30px; line-height: 30px; } input { height: 25px; } button { width: 100px; height: 35px; } .tips { float: left; text-align: right; } .input { float: left; text-align: left; } #prompt { color: red; } </style> </head> <body> <div class = "box"> <h3>請(qǐng)登錄</h3> <form> <div class = "tips"> <p><label for = "username">用戶名:</label></p> <p><label for = "password">密碼:</label></p> </div> <div class = "input"> <p><input type = "text" name = "username" id = "username"></p> <p><input type = "password" name = "password" id = "password"></p> <p> <button type = "button">登錄</button> </p> </div> </form> <p id = "prompt"></p> </div> </body> <script> let btn = document.getElementsByTagName('button')[0]; btn.onclick = function () { // 創(chuàng)建xhr對(duì)象 let xhr = new XMLHttpRequest(); // 監(jiān)聽響應(yīng)狀態(tài) -- 每當(dāng)readyState改變時(shí),就會(huì)觸發(fā)onreadystatechange事件。 xhr.onreadystatechange = function () { // readyState為4時(shí):請(qǐng)求已完成,且響應(yīng)已就緒 if (xhr.readyState === 4) { // status的值,200:‘OK';404:未找到頁(yè)面 if (xhr.status === 200) { let prompt = document.getElementById('prompt'); let json = JSON.parse(xhr.responseText); // console.log(json); prompt.innerHTML = json['msg']; setTimeout(function () { if (json['status'] === 1) { location.href = 'admin.php'; } else if (json['status'] === 0) { document.getElementsByName('username')[0].value = ''; document.getElementsByName('password')[0].value = ''; prompt.innerHTML = ''; } }, 3000); } } }; // 設(shè)置請(qǐng)求參數(shù) xhr.open('post', 'check.php', true); // 設(shè)置頭信息,將內(nèi)容類型設(shè)置為表單提交方式 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 發(fā)送請(qǐng)求數(shù)據(jù) let date = { username: document.getElementsByName('username')[0].value, password: document.getElementsByName('password')[0].value }; let dateJson = JSON.stringify(date); xhr.send('date=' + dateJson); }; </script> </html>
<?php // 用于驗(yàn)證的數(shù)據(jù) $db = [ [ 'username' => 'admin', 'password' => '000000', ], [ 'username' => 'admin1', 'password' => '111111', ], [ 'username' => 'admin2', 'password' => '222222', ], ]; //獲取post的數(shù)據(jù) $date = json_decode( $_POST[ 'date' ] ); $username = $date->username; $password = $date->password; // 檢測(cè)用戶是否存在 foreach ( $db as $value ){ if ( $value[ 'username' ] === $username ){ if ( $value[ 'password' ] === $password ){ echo json_encode( [ 'status' => 1, 'msg' => '登錄成功,正在跳轉(zhuǎn)…' ] ); exit; } } } echo json_encode( [ 'status' => 0, 'msg' => '用戶名或密碼錯(cuò)誤,請(qǐng)重試' ] );
<?php echo '<h3 align="center"> 后臺(tái)管理中心</h3 >';
批改老師:天蓬老師批改時(shí)間:2019-02-14 09:11:23
老師總結(jié):寫得還算完整, 前后臺(tái)交互的邏輯是正確的