abstrait: <!DOCTYPE html> <html> <head> <title>Ajax原理實(shí)線</title> <meta charset="utf-8"> </head> <body> <form accept-charset="
<!DOCTYPE html> <html> <head> <title>Ajax原理實(shí)線</title> <meta charset="utf-8"> </head> <body> <form accept-charset="utf-8"> <label>郵箱:</label> <input type="email" name="email" id="email"><br><br> <label>密碼</label> <input type="password" name="password" placeholder="" id="password"><br> <input type="button" name="" value="提交" id='btn'><br> </form> <script type="text/javascript"> // 1.創(chuàng)建Ajax對(duì)象 // let email = document.getElementById("email"); // let e = email.value // let password = ; // console.log(password) let btn = document.getElementById("btn"); btn.onclick= function(){ let xhr = new XMLHttpRequest(); // 2.啟動(dòng)監(jiān)聽(tīng) xhr.onreadystatechange = function () { if (xhr.readyState=== 4 ){ //請(qǐng)求成功需要操作的內(nèi)容 if (xhr.status===200) { // 響應(yīng)成功 let ps = document.createElement('p'); let enjson = JSON.parse(xhr.responseText); //JSON.parse()方法可以將服務(wù)器發(fā)送過(guò)來(lái)的JSON格式解析成JS的對(duì)象 if (enjson['status']===1) { ps.innerHTML=enjson['msg']; }else if (enjson['status']===0){ ps.innerHTML=enjson['msg']; } document.body.appendChild(ps); setTimeout(function(){ //計(jì)時(shí)器 location.href='admin.php'; }, 2000) }else { // 響應(yīng)失敗 } }else{ // 如果請(qǐng)求在繼續(xù)那么可以輸出一張圖片 } } let json = { email:document.getElementById("email").value, password:document.getElementById("password").value } json = JSON.stringify(json); //將JS對(duì)象轉(zhuǎn)為字符串 // 3.發(fā)送請(qǐng)求 xhr.open('post', 'check.php', true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //POST要修改請(qǐng)求頭 xhr.send("data="+json);//手動(dòng)添加一個(gè)鍵,拼接json變量的值,發(fā)送到服務(wù)器 } </script> </body> </html>
<?php $data = $_POST['data']; $data = json_decode($data); $email = $data->email; $password = $data->password; $dbh = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); $sql="SELECT `password`,`email`,`name` FROM `user` WHERE `email`=:email AND `password`=:password"; $stmt = $dbh->prepare($sql); $stmt->bindparam(':password',$password,PDO::PARAM_STR); $stmt->bindparam(':email',$email,PDO::PARAM_STR); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC); //由數(shù)據(jù)返回值,沒(méi)有返回false if ($user) { session_start(); //啟動(dòng)會(huì)話 $_SESSION['username']= $user['name']; //生成會(huì)話標(biāo)識(shí)。 echo json_encode(['status'=>1,'msg'=>'登陸成功正在跳轉(zhuǎn)']); //json_encode函數(shù)將數(shù)組格式化為JSON格式。 }else{ echo json_encode(['status'=>0,'msg'=>'登陸失敗']); } ?>
Professeur correcteur:天蓬老師Temps de correction:2019-04-22 10:04:09
Résumé du professeur:php誕生時(shí)的主要用途, 就是進(jìn)行服務(wù)器端的表單驗(yàn)證的, 所有, 從表單驗(yàn)證來(lái)實(shí)習(xí), 是一個(gè)最佳的辦法, 這里面有很多的有趣的知識(shí)點(diǎn)...
ajax是從用戶體驗(yàn)上, 對(duì)表單驗(yàn)證進(jìn)行處理..., 并不是什么新技術(shù), 只是對(duì)已存在的技術(shù)一個(gè)優(yōu)化或應(yīng)用范圍的擴(kuò)展...