使用php跳轉界面和AJAX都可實現登錄界面的跳轉的登錄失敗對的提醒。但是,php跳轉的方式
需要額外加載其他界面,用戶體驗差。AJAX可實現當前頁面只刷新需要的數據,不對當前網頁進行
重新加載或者是跳轉。
做一個簡單的登錄界面:
<div id=""> 用戶名 : <input type="text" name="" id="uid" value="" /> </div> <div id=""> 密 碼 : <input type="text" name="" id="pwd" value="" /> </div> <div id=""> <input type="button" name="" id="denglu" value="登錄" /> </div>

然後是js代碼,使用jq比較簡單,所以要先引入jq文件包。
其次獲取用戶名和密碼的值:
var uid = $("#uid").val();
var pwd = $("#pwd").val();
設置好之後就可以進行AJAX的設置了:
$.ajax({
type: "post",
url: "dengluchuli.php",
data: {
u: uid,
p: pwd
},
dataType: "TEXT",
success: function(r) { //r為返回值
if(r.trim() == "y") { //y為 url跳轉網頁中傳回的值。
window.location.href = "跳轉界面";
} else {
alert("用戶名或密碼錯誤");
}
}
});
dengluchuli.php:
<?php
include("AJAXLOGIN.class.php");
$dd = new LoGin($_POST["u"],$_POST["p"]);
$ae = $dd::logi("login","username","password","name"); //分別是數據庫中的 表名,表中的用戶名,密碼,姓名(數據從數據庫中導入)
?>

這裡我引入了一個登錄類(AJAXLOGIN.class.php),是為了以後方便使用:
<?php
class DBDA
{
public $host="localhost";
public $uid = "root";
public $pwd = "";
public $dbname = "12345";
//成員方法
public function Query($sql,$type=1)
{
$db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
$r = $db->query($sql);
if($type==1)
{
return $r->fetch_all();
}
else
{
return $r;
}
}
}
class LoGin
{
public static $uid ;
public static $pwd ;
function __construct($x,$y)
{
self::$uid = $x;
self::$pwd = $y;
}
static function logi ($table,$username,$password,$name){
$db = new DBDA();
$nnn = self::$uid;
$sql = " select $name,$password from $table where $username='$nnn '" ;
$at = $db->Query($sql);
$p = self::$pwd;
if(!empty($p) && $p==$at[0][1])
{
$_SESSION["uid"]= $at[0][0];
echo "y";
}
else{
echo "n";
}
}
}
?>
登錄界面完整代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="../jquery-1.11.2.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="">
用戶名 :
<input type="text" name="" id="uid" value="" />
</div>
<div id="">
密 碼 :
<input type="text" name="" id="pwd" value="" />
</div>
<div id="">
<input type="button" name="" id="denglu" value="登錄" />
</div>
</body>
<script type="text/javascript">
$("#denglu").click(function() {
var uid = $("#uid").val();
var pwd = $("#pwd").val();
$.ajax({
type: "post",
url: "dengluchuli.php",
data: {
u: uid,
p: pwd
},
dataType: "TEXT",
success: function(r) {
if(r.trim() == "y") {
window.location.href = "ppp.php";
} else {
alert("用戶名或密碼錯誤");
}
}
});
})</script>
</html>