一.ajax完成用戶名異步檢驗
html代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用戶名是否存在</title> </head> <body> <form action="" method="post"> <table> <tr> <td>用戶名</td> <td><input type="text" name="username" placeholder="請輸入用戶名" class="name" id="name" ></td> <td><span class="note"></span></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="password" class="pwd" ></td> </tr> <tr><td><input type="submit" id="check"></td></tr> </table> </form> </body> </html>
js代碼(當鼠標移開用戶名標簽時,ajax引擎自動與后台實現異步交互,從而完成驗證)
<script type="text/javascript"> var name=document.getElementById('name'); var pwd=document.getElementsByClassName('pwd')[0]; document.querySelector('.name').onblur=function () { document.querySelector('.note').innerHTML='驗證中……'; //1.創建對象 var xhr=new XMLHttpRequest(); //2.設置請求行(get請求數據寫在url后面) xhr.open('post','check.php'); //3.設置請求頭(get請求可以省略,post不發送數據也可以省略) xhr.setRequestHeader('content-type',"application/x-www-form-urlencoded"); //3.5注冊回調函數 xhr.onload=function () { if(xhr.status==200 && xhr.readyState==4) { console.log(xhr.responseText); var data=JSON.parse(xhr.responseText); console.log(data); if(data.flag==3) { document.querySelector('.note').innerHTML = data.msg; } } }; //4.請求主體發送(get請求為空,或者寫null,post請求數據寫在這里,如果沒有數據,直接為空或者寫null) //post請求發送數據 寫在send中 //key=value&key2=value2 xhr.send("username="+document.getElementById('name').value); }; </script>
后台php文件(check_username.php):
<?php //print_r($_POST); $flag=0; $msg='failure'; $username=isset($_POST['username'])?$_POST['username']:""; $password=isset($_POST['password'])?$_POST['password']:""; if($username==='admin'){ $flag=3; $msg='用戶名正確'; }else { $flag=3; $msg='用戶名不存在'; } ?>
效果如下:
知識點-----AJAX - onreadystatechange 事件
當發送一個請求后,客戶端需要確定這個請求什么時候會完成,因此,XMLHttpRequest對象提供了onreadystatechange
事件機制來捕獲請求的狀態,繼而實現響應。
當請求被發送到服務器時,我們需要執行一些基於響應的任務。
每當readyState
改變時,就會觸發onreadystatechange
事件。
readyState
屬性存有 XMLHttpRequest 的狀態信息。
下面是 XMLHttpRequest 對象的三個重要的屬性:
注意:POST請求不加請求頭,數據是傳不到后台的
二.提交時完成后用戶名與密碼的驗證
創建一個后台文件(check_login.php)用來驗證用戶名與密碼
新建php文件check_login.php(用戶數據這里寫死,一般是從數據庫查詢得到的)
$username=isset($_POST['username'])?$_POST['username']:""; $password=isset($_POST['password'])?$_POST['password']:""; if($username=='admin' && $password==123){ $flag=1; $msg='登錄成功'; } else { $flag=2; $msg='密碼錯誤'; } $response=[ 'flag'=>$flag, 'msg'=>$msg, ]; echo json_encode($response);
在原來的登錄界面的js腳本里加入點擊時的驗證
document.getElementById('check').onclick=function () { var xhr=new XMLHttpRequest(); xhr.open('post','check_login.php'); xhr.setRequestHeader('content-type',"application/x-www-form-urlencoded"); xhr.onreadystatechange=function () { if(xhr.readyState==4 && xhr.status==200){ var data=JSON.parse(xhr.responseText); if(data.flag==1) { alert(data.msg); console.log(data); }else if(data.flag==2){ alert(data.msg); console.log(data); } } }; xhr.send('username='+document.getElementById('name').value+'&password='+pwd.value); }
效果:
如果出現上面的錯誤,應該是后台文件寫錯了,檢查一下。