本文實例講述了原生javascript的ajax請求及后臺PHP響應操作。分享給大家供大家參考,具體如下:
<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <table id="t"> <tr> <td>學號:</td> <td><input type="text" id="stuid" /></td> </tr> <tr> <td>密碼:</td> <td><input type="password" id="stupass" /></td> </tr> <tr> <td colspan="2"> <input id="btnLogin" type="button" value="登錄" /> </td> </tr> </table></body></html>
ajax的一般步驟
1、創建對象
let xhr = new XMLHttpRequest();
2、設置請求參數
xhr.open(請求方式,請求地址,是否異步);
3、設置回調函數
xhr.onreadystatechange = function () { // 5、接收響應 alert(xhr.responseText);}4、發送
xhr.send();
<script type="text/javascript">window.onload = function(){ $("#btnLogin").onclick = function(){ //1、創建對象 let xhr = new XMLHttpRequest(); //2、設置請求參數 xhr.open('post','loginCheckajax.php',true); //3、設置回調函數 xhr.onreadystatechange = function(){ if(xhr.readyState==4 && xhr.status==200){ if(xhr.responseText=='1'){ //存cookie saveCookie("username",$("#stuid").value,7); //挑到首頁 location.href="index.html" rel="external nofollow" ; }else{ alert("登錄失敗!"); } } } xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //4、發送 xhr.send("stuid="+$("#stuid").value+"&stupass="+$("#stupass").value); }}function $(str){ //id class tagname if(str.charAt(0) == "#"){ return document.getElementById(str.substring(1)); }else if(str.charAt(0) == "."){ return document.getElementsByClassName(str.substring(1)); }else{ return document.getElementsByTagName(str); }}</script>php文件
<?php header("Content-type:text/html;charset=utf-8"); //一、獲取用戶的輸入 $stuid = $_POST['stuid']; $stupass = $_POST['stupass']; //二、處理 //1、建立連接(搭橋) $conn = mysql_connect('localhost','root','root'); if(!$conn){ die("連接失敗"); } //2、選擇數據庫(選擇目的地) mysql_select_db("mydb1809",$conn); //3、執行SQL語句(傳輸數據) $sqlstr="select * from student where stuid='$stuid' and stupass='$stupass'"; $result = mysql_query($sqlstr,$conn);//結果是個表格 //4、關閉數據庫(過河拆橋) mysql_close($conn); //三、響應 if(mysql_num_rows($result)>0){ echo "1"; }else{ echo "0"; }?>
新聞熱點
疑難解答
圖片精選