首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

原生 JavaScript + PHP 實作 AJAX 登入完整範例

     編輯:更多程式設計知識

雖然 jQuery `$.ajax` 簡潔易用,但理解原生 `XMLHttpRequest` 運作機制有助於除錯與效能調優。本文提供一個完整的「使用者名稱/密碼登入」範例,涵蓋 HTML 表單、原生 JS AJAX 流程、PHP 後端驗證。

前端 HTML (index.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AJAX 登入範例</title>
    <script src="ajax.js"></script>
</head>
<body>
    用戶名:<input id="userName" type="text"><br>
    密碼:<input id="passWord" type="password"><br>
    <span id="showInputError" style="color:red; font-weight:bold;"></span><br>
    <input type="button" value="登入" onclick="doLogin()">
</body>
</html>

原生 JavaScript (ajax.js)

var xhr = null;

function doLogin() {
    var user = document.getElementById("userName").value;
    var pass = document.getElementById("passWord").value;
    var errEl = document.getElementById("showInputError");

    if (!user) { errEl.innerHTML = "用戶名不能為空"; return; }

    xhr = createXHR();
    if (!xhr) { alert("瀏覽器不支援 XMLHttpRequest"); return; }

    var url = "login.php?userName=" + encodeURIComponent(user) +
              "&passWord=" + encodeURIComponent(pass) +
              "&t=" + Math.random();  // 防快取

    xhr.onreadystatechange = handleResponse;
    xhr.open("GET", url, true);
    xhr.send(null);
}

function handleResponse() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            var resp = xhr.responseText.trim();
            if (resp === "yes") {
                window.location.href = "main.php";  // 登入成功跳轉
            } else {
                document.getElementById("showInputError").innerHTML = "用戶名或密碼錯誤";
            }
        } else {
            document.getElementById("showInputError").innerHTML = "伺服器錯誤: " + xhr.status;
        }
    }
}

function createXHR() {
    if (window.XMLHttpRequest) return new XMLHttpRequest();  // 標準瀏覽器
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}  // IE6+
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}  // IE5
    return null;
}

後端 PHP (login.php)

<?php
header("Content-Type: text/plain; charset=utf-8");

$user = $_GET["userName"] ?? "";
$pwd  = $_GET["passWord"] ?? "";

$conn = mysqli_connect("localhost", "root", "123456", "my_test");
if (!$conn) { echo "no"; exit; }
mysqli_set_charset($conn, "utf8");

$stmt = $conn->prepare("SELECT 1 FROM Userinfo WHERE userName=? AND pwd=?");
$stmt->bind_param("ss", $user, $pwd);
$stmt->execute();
$stmt->store_result();

echo ($stmt->num_rows > 0) ? "yes" : "no";

$stmt->close();
$conn->close();
?>

關鍵點解析

  1. 防快取:URL 附加隨機參數 `t=Math.random()`,避免 IE 缓存 GET 請求。
  2. 編碼安全:前端 `encodeURIComponent`,後端 `mysqli_set_charset("utf8")`,資料庫欄位同為 utf8。
  3. 防 SQL 注入:PHP 使用 **預處理語句** (`prepare`/`bind_param`),原範例直接拼接字串極度危險,已修正。
  4. 狀態碼檢查:`readyState===4` 且 `status===200` 才處理回應。
  5. 相容性:`createXHR()` 涵蓋標準瀏覽器、IE6+、IE5。

現代化替代方案

// Fetch API (現代瀏覽器)
fetch(`login.php?userName=${encodeURIComponent(user)}&passWord=${encodeURIComponent(pass)}`)
  .then(r => r.text())
  .then(t => t.trim() === "yes" ? location.href="main.php" : showError("錯誤"));

或使用 `axios`、`jQuery.ajax` 簡化錯誤處理、攔截器、取消請求等進階功能。

總結

原生 AJAX 核心流程:建立 XHR → 註冊 `onreadystatechange` → `open` → `send` → 回調中判斷 `readyState`/`status` → 處理 `responseText`。理解此流程能讓你在任何框架失效或不適用時,快速撰寫輕量級非同步請求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved