摘要:HTML代碼:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</
HTML代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <p>登錄表單</p> <p>用戶名:<input type="text" name="username" class="username"></p> <p>密 碼:<input type="text" name="password" class="password"></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){ if(xhr.status===200){ let p=document.createElement('p'); p.style.color='red'; //設(shè)置一個變量,將服務(wù)器端返回的值轉(zhuǎn)化成json格式 let json=JSON.parse(xhr.responseText); // console.log(json); 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='inc/admin.php';//登錄成功后跳轉(zhuǎn)地址 } },2000) }else{ alert('相應(yīng)失敗'+xhr.status); } }else{ //圖片不停的轉(zhuǎn)動 } } //3、設(shè)置請求參數(shù) xhr.open('post','inc/check.php',true); //4、設(shè)置請求頭部 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //5、獲取表單數(shù)據(jù) let data={ username:document.getElementsByName('username')[0].value, password:document.getElementsByName('password')[0].value } let data_json=JSON.stringify(data);//將json轉(zhuǎn)化成文本 xhr.send('data='+data_json); } </script> </body> </html>
check.php代碼:
<?php $user=json_decode($_POST['data']); $username=$user->username; $password=sha1($user->password); $pdo=new PDO('mysql:host=127.0.0.1;dbname=a','root','root'); $sql="select count(*) from dede_admin where uname='{$username}' and pwd='{$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>歡迎來到系統(tǒng)管理后臺</h2>';
自己本地有搭建好的數(shù)據(jù)庫,自己建了一個本地的數(shù)據(jù)庫和帳號密碼。
第一次體驗(yàn)了一把傳說中的html+Ajax+php登錄帳號。感覺爽歪歪。
由于對與前端和交互代碼不熟悉。表示要多練習(xí)幾遍。筆記記下來。
感謝老師
批改老師:天蓬老師批改時間:2019-02-11 13:47:41
老師總結(jié):是不是沒有你想像的那么困難呢? 其實(shí)很簡單的, 只要按套路走就行