萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

原生 JavaScript 實作 AJAX 登入流程(HTML + JS + PHP)

教學目的

雖然 jQuery 封裝了便利的 $.ajax(),但理解原生 XMLHttpRequest 流程有助於掌握底層運作,便於除錯與輕量化專案。

三檔案架構

1. index.html — 介面

<input id="userName" type="text" placeholder="用戶名">
<input id="passWord" type="password" placeholder="密碼">
<span id="showInputError" style="color:red;font-weight:bold"></span><br>
<input type="button" value="登入" onclick="showSelect()">
<script src="js/ajaxTest.js"></script>

2. ajaxTest.js — 邏輯

var xmlHttp;

function showSelect() {
    var userName = document.getElementById("userName").value;
    var passWord = document.getElementById("passWord").value;
    if (!userName.length) {
        document.getElementById("showInputError").innerHTML = "用戶名不能為空";
        return;
    }

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

    var url = "ajaxTest.php?userName=" + encodeURIComponent(userName)
            + "&passWord=" + encodeURIComponent(passWord)
            + "&sid=" + Math.random(); // 防快取

    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function stateChanged() {
    if (xmlHttp.readyState === 4 || xmlHttp.readyState === "complete") {
        var resp = xmlHttp.responseText;
        if (resp === "yes") {
            self.location = 'Main.php';
        } else {
            document.getElementById("showInputError").innerHTML = "用戶名或密碼錯誤";
        }
    }
}

function GetXmlHttpObject() {
    var xmlHttp = null;
    try { xmlHttp = new XMLHttpRequest(); }              // 現代瀏覽器
    catch (e) {
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } // IE 6+
        catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } // IE 5
    }
    return xmlHttp;
}

3. ajaxTest.php — 後端驗證

<?php
$userName = $_GET["userName"];
$pwd = $_GET["passWord"];
$con = mysql_connect("localhost", "root", "123456");
mysql_select_db("my_test", $con);
mysql_query("SET NAMES utf8");

$sql = "SELECT * FROM Userinfo WHERE userName='$userName' AND pwd='$pwd'";
$result = mysql_query($sql);
echo (mysql_num_rows($result) > 0) ? "yes" : "no";
mysql_close($con);
?>

安全性提醒

  • 範例使用舊版 mysql_* 函式,實務請改用 mysqli 或 PDO 並採用預處理語句防止 SQL 注入。
  • 密碼不應明文儲存,需以 password_hash() 加鹽雜湊。
  • 生產環境請強制 HTTPS,避免帳號密碼明文傳輸。
copyright © 萬盛學電腦網 all rights reserved