abstract:后臺(tái)代碼: $user = json_decode($_POST['data']); //print_r($_POST);die; $users=[]; $users['email']=$user->email; $users['password']=$user->password; //print_r($users
后臺(tái)代碼:
$user = json_decode($_POST['data']); //print_r($_POST);die; $users=[]; $users['email']=$user->email; $users['password']=$user->password; //print_r($users); $arrs=[]; $arrs=[['email'=>'admin@123.php','password'=>'123456'],['email'=>'peter@123.php','password'=>'123456']]; //$arr=['email'=>'admin@123.php','password'=>'123456']; foreach ($arrs as $arr) { if ($arr==$users){ echo json_encode(['status'=>1,'msg'=>'登錄成功,正在跳轉(zhuǎn)...']) ; exit; }else{ echo json_encode(['status'=>0,'msg'=>'郵箱或密碼錯(cuò)誤,登錄失敗!']) ; exit; } }
前臺(tái)代碼:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <h1>用戶登錄</h1> <form> <p>郵箱: <input type="email" name="email"></p> <p>密碼: <input type="password" name="password"></p> <p><button type="button">提交</button></p> </form> </div> <script> var btn=document.getElementsByTagName('button')[0]; btn.onclick=function () { var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function () { }; //2.監(jiān)聽(tīng)響應(yīng)狀態(tài) xhr.onreadystatechange = function(){ if (xhr.readyState === 4) { // 準(zhǔn)備就緒 // 判斷響應(yīng)結(jié)果: if (xhr.status === 200) { // 響應(yīng)成功,通過(guò)xhr對(duì)象的responseText屬性可以獲取響應(yīng)的文本,此時(shí)是html文檔內(nèi)容 var p = document.createElement('p'); //創(chuàng)建新元素放返回的內(nèi)容 p.style.color = 'red'; var json = JSON.parse(xhr.responseText); if (json.status === 1) { p.innerHTML = json.msg; } else if (json.status == 0) { p.innerHTML = json.msg; } // 將響應(yīng)文本添加到新元素上 document.forms[0].appendChild(p); // 將新元素插入到當(dāng)前頁(yè)面中 btn.disabled = true; setTimeout(function(){ document.forms[0].removeChild(p); btn.disabled = false; if (json.status == 1) { location.href = 'admin.php'; } },2000); } else { // 響應(yīng)失敗,并根據(jù)響應(yīng)碼判斷失敗原因 alert('響應(yīng)失敗'+xhr.status); } } else { // http請(qǐng)求仍在繼續(xù),這里可以顯示一個(gè)一直轉(zhuǎn)來(lái)轉(zhuǎn)去的圖片 } } //3.設(shè)置請(qǐng)求參數(shù) xhr.open('post','inc/check.php',true); //4. 設(shè)置頭信息,將內(nèi)容類型設(shè)置為表單提交方式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //4.發(fā)送請(qǐng)求 var data = { email: document.getElementsByName('email')[0].value, password: document.getElementsByName('password')[0].value }; // data = 'email='+data.email+'&password='+data.password; var data_json=JSON.stringify(data); xhr.send('data='+data_json); }; </script> </body> </html>
Correcting teacher:查無(wú)此人Correction time:2019-05-16 09:09:55
Teacher's summary:完成的不錯(cuò),json數(shù)據(jù)可以在不同的編程語(yǔ)言中傳遞數(shù)據(jù)。好好練習(xí),繼續(xù)加油