萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

純 HTML 頁面實現表單提交、參數傳遞與身份驗證的實戰方案

核心觀念:純 HTML 無法獨立完成後端邏輯

HTML 是靜態標記語言,無法直接寫入資料庫、驗證 Session 或處理商業邏輯。實務上採用「前端純 HTML + 後端 API」架構:前端負責呈現與蒐集資料,後端(PHP、Node.js、Python、C# 等)負責處理與儲存。

一、表單提交:<form> 標籤

<form action="saveData.php" method="POST">
  <label>姓名:<input type="text" name="username" required></label>
  <label>信箱:<input type="email" name="email" required></label>
  <button type="submit">送出</button>
</form>
  • action:後端處理端點(可為 .php、.aspx、/api/endpoint)。
  • method="POST":資料放在 Request Body,不顯示於 URL,適合敏感資料。
  • method="GET":資料附加於 URL 查詢字串,適合搜尋、分頁等冪等操作。
  • 亦可搭配 JavaScript fetch() / XMLHttpRequest 發送 AJAX,體驗更佳。

二、參數傳遞:查詢字串 + JavaScript 解析

靜態頁面無法直接讀取伺服器 Session,需透過 URL 查詢字串傳遞識別碼,再由前端 JS 解析並呼叫 API 取得資料。

URL 範例

survey.html?userId=12345&surveyId=789

通用解析函式(原生 JS)

function getQueryParam(name) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(name);  // 現代瀏覽器原生支援,無需正則
}

// 使用範例
const userId = getQueryParam('userId');
if (userId) {
  fetch(`/api/survey/${userId}`)
    .then(res => res.json())
    .then(data => populateForm(data));
}

舊版瀏覽器相容寫法: 使用 RegExp 解析 window.location.search(原文範例)。

替代方案:後端模板引擎注入

若後端渲染模板(如 JSP、Thymeleaf、Razor),可直接將參數注入頁面:

<input type="hidden" name="userId" value="${session.userId}">

三、身份驗證:前端攔截 + 後端驗證

流程架構

  1. 使用者登入 → 後端建立 Session / 發行 JWT Token → 存入 Cookie / LocalStorage。
  2. 進入問卷頁 → 前端 JS 檢查 Token 存在性 → 無則導向登入頁。
  3. 前端定期(或每次關鍵操作)呼叫 /api/auth/check 驗證 Token 有效性。
  4. 後端 API 統一攔截器驗證 Token,失效回 401,前端統一處理導向登入。

前端驗證範例(AJAX 檢查 Session)

async function checkAuth() {
  try {
    const res = await fetch('/api/auth/status', { credentials: 'include' });
    if (!res.ok) throw new Error('未登入或逾期');
    const data = await res.json();
    return data.isAuthenticated;
  } catch (e) {
    window.location.href = '/login.html?redirect=' + encodeURIComponent(location.href);
    return false;
  }
}

// 頁面載入時呼叫
document.addEventListener('DOMContentLoaded', () => {
  checkAuth().then(auth => { if (!auth) return; initSurvey(); });
});

完整架構圖解


+----------------+        HTTP Request        +----------------+
|  靜態 HTML 頁面  |  ----------------------->  |  後端 API 伺服器  |
|  (CDN/靜態主機)  |  form submit / fetch()     |  (驗證、儲存、業務) |
+----------------+        JSON / Redirect     +----------------+
        ^                                               |
        |              靜態資源 (JS/CSS/圖片)            |
        +-----------------------------------------------+

安全性關鍵點

  • CSRF 防護: 表單隱藏 csrf_token,後端驗證;或使用 SameSite Cookie。
  • XSS 防護: 後端輸出編碼、前端避免 innerHTML 插入不可信資料、設定 CSP 標頭。
  • 敏感資料: 傳輸全程 HTTPS,密碼勿出現在 URL(勿用 GET 提交密碼)。
  • 驗證前移: 前端驗證僅為 UX,後端必須再次完整驗證。
copyright © 萬盛學電腦網 all rights reserved