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 查詢字串,適合搜尋、分頁等冪等操作。fetch() / XMLHttpRequest 發送 AJAX,體驗更佳。靜態頁面無法直接讀取伺服器 Session,需透過 URL 查詢字串傳遞識別碼,再由前端 JS 解析並呼叫 API 取得資料。
survey.html?userId=12345&surveyId=789
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}">
/api/auth/check 驗證 Token 有效性。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_token,後端驗證;或使用 SameSite Cookie。innerHTML 插入不可信資料、設定 CSP 標頭。