登入驗證幾乎每個網站都用得到,結合 PHP 與 AJAX 就能做到不必重整頁面即可完成驗證。以下提供完整的程式碼與說明。
先看 chklogin.php 這個頁面,它負責連線資料庫並比對帳號密碼:
<?php
session_start();
$connect = mysql_connect("127.0.0.1", "root", "123");
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("design", $connect);
$query = "select * from ta_user where user_name ='" . $name . "'";
$result = mysql_query($query) OR die("Unable to connect to MySQL");
$rows = mysql_fetch_array($result);
if ($rows['user_password'] == $pwd) {
header("Location:login_suss.php?name=" . $name);
} else {
echo "<table width='235' height='61' border='0' align='center'>";
echo "<tr><td height='29'>用戶名或密碼錯誤!</td></tr>";
echo "<tr><td height='29'>請點擊<a href='Javascript:history.go(-1);'>這兒</a>重新輸入!</td></tr>";
echo "</table>";
}
?>
接著在前端建立 XMLHttpRequest 物件,並把使用者輸入的帳號送到後端比對:
<script language="Javascript">
function getXMLHTTPRequest() {
var xRequest = null;
if (window.XMLHttpRequest) {
xRequest = new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
xRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
return xRequest;
}
function Ajax(url) {
AjaxObj = getXMLHTTPRequest();
AjaxObj.onreadystatechange = processRequest;
AjaxObj.open("post", url, true);
AjaxObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AjaxObj.send("name=" + name);
}
function processRequest() {
if (AjaxObj.readyState == 4) {
if (AjaxObj.status == 200) {
if (AjaxObj.responseText != "") {
document.getElementById("show").innerHTML = AjaxObj.responseText;
}
} else {
alert("您所請求的頁面有異常。");
}
} else {
document.getElementById("show").innerHTML = "Loading......";
}
}
</script>
實際應用時,只要在適當時機呼叫 Ajax(url) 函式,就能完成無重整的登入驗證流程。