參考自博主“讓心開始”的文章https://www.cnblogs.com/cuikang/p/5260558.html,感覺例子基本功能有登陸交互了,簡單明了,可以做參考,后面我這個懶蟲慢慢改進吧。
先是index.html
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ajaxLogin</title>
<!--懶得下jquery,直接線上引用地址-->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<!--ajax不用刷新頁面-->
<h1>登錄頁面</h1>
<div>用戶名:<input type="text" id="uid" /></div><br />
<div>密 碼:<input type="text" id="pwd" /></div><br />
<div><input type="button" value="登陸" id="btn"/></div><br />
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$("#btn").click(function(){
var uid = $("#uid").val();
var pwd = $("#pwd").val();
$.ajax({ //Json數(shù)據(jù)
url:"chuli.php",//傳輸?shù)侥膫€頁面處理
data:{uid:uid,pwd:pwd},//傳輸哪些數(shù)據(jù)過去Json
type:"POST",//傳輸方式
dataType:"TEXT",//返回類型 字符串
success: function(data){ //執(zhí)行成功之后執(zhí)行的方法 又稱為回調(diào)函數(shù)
if(data == "OK")
{
//登錄成功操作,這里是跳到4399
window.location= "http://www.4399.com";
}
else
{
alert(data);
}
}
});
})
});
</script>
</html>
然后到chuli.php
$uid=$_POST["uid"];
$pwd=$_POST["pwd"];
//數(shù)據(jù)庫ip(放在服務器本地就直接localhost),數(shù)據(jù)庫賬號,數(shù)據(jù)庫密碼,你所用的數(shù)據(jù)庫名稱
$db=new mysqli("localhost","root","root","test");
if(mysqli_connect_error())
{
echo "連接錯誤";
}
else
{
//user2是用戶信息所在的表,分別有username和password兩項,需要對應起來
$sql="select count(*) from user2 where username='".$uid."' and password='".$pwd."'";
$result=$db->query($sql);
$row=$result->fetch_row();
if($row[0]==0)
{
echo "用戶名或密碼錯誤";
}
else
{
echo "OK";
}
}
?>
把這兩個文件放在同一個文件夾,直接拖到phpstudy的WWW根目錄下,然后試試在瀏覽器中訪問,就可以了。