1. 程式人生 > >使用原生AJAX 發送異步請求實現 常用的用戶登錄效果

使用原生AJAX 發送異步請求實現 常用的用戶登錄效果

tor dia post request reat def cat inner -c

HTML部分

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>...</title>
  <style type="text/css">
	.modal{
		position:fixed;
		left:0;top:0;bottom:0;right:0;
		background:rgba(0,0,0,.2);
		display:none;
	}
	.modal.active {
		display:block;
	}
	.modal-dialog{
		width:350px;
		margin:10% auto;
	}
	.modal-content{
		background:#fff;
		border-radius:5px;
		padding:30px;
	}
	.erro{
		width:100%;
		color:red;
	}
  </style>
 </head>
 <body>
		<p id="loginArea"> 
			<a href="#" id="btLogin">用戶登錄</a>
		</p>
		<div class="modal" id="modalLogin">  <!--模態框遮罩層-->
			<div class="modal-dialog">
				<div class="modal-content">
					<br>
						手機號: <input type="text" name="phone"><br>
						密碼號: <input type="passwrod" name="pwd"><br>
						<input id="sub" type="button" value="提交">
				</div>	
			</div>
		</div>
		<script type="text/javascript">
			btLogin.onclick = function(e){     //綁定模態框點擊顯示行為
				e.preventDefault(); 
				modalLogin.className="modal active";
			} 
			sub.onclick=function(){      // 綁定異步提交數據方法
				var ph = document.querySelectorAll("input")[0].value;
				var pw = document.querySelectorAll("input")[1].value;
				//console.log(ph,pw);
				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function(){
					if(xhr.readyState===4){
						if(xhr.status===200){
							doResponse(xhr,ph);
						}else{
							console.log("請求失敗")
						}
					}
				}
				xhr.open("POST","mail_login.php",true);
				xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");    // POST 方法需要設置請求頭部
				xhr.send("phone="+ph+"&pwd="+pw);
				function doResponse(xhr,ph){    // 響應處理函數
					if(xhr.responseText==="succ"){
						modalLogin.className="modal";
						var span = document.createElement("span");
						span.innerHTML="歡迎回來:"+ph;
						loginArea.removeChild(loginArea.children[0]);
						loginArea.appendChild(span);
					}else if(xhr.responseText==="err"){
						var div = document.querySelector(".modal-content");
						var span = document.createElement("span");
						span.innerHTML="用戶名或密碼有誤";
						span.className="erro";
						div.insertBefore(span,div.firstChild);
					}	
				}
			}
		</script>
 </body>
</html>

  

簡單的PHP 響應如下

<?php
@$ph = $_REQUEST[‘phone‘] or die(‘phone required‘);
@$pw = $_REQUEST[‘pwd‘] or die(‘pwd required‘);
$conn =mysqli_connect(‘127.0.0.1‘,‘root‘,‘‘,‘sohu‘,3306);
$sql = "SET NAMES UTF8";
mysqli_query($conn,$sql);
$sql = "SELECT * FROM mail WHERE phone=‘$ph‘ AND pwd=‘$pw‘";
$result = mysqli_query($conn,$sql);
$list = mysqli_fetch_row($result);
if($list===null){
	echo "err";
}else{
	echo "succ";
}

  

使用原生AJAX 發送異步請求實現 常用的用戶登錄效果