<html>
<head>
<title>demo</title>
<meta name="Author" content="xugang">
</head>
<body>
<form name="frm" method="get" action="b.html" onsubmit="return foo()">
<input type="hidden" id="hid" value="123" name="hid">
<input type="submit" value="提交">
</form>
</body>
</html>
<html>
<head>
<title>接收頁面</title>
</head>
<body>
<script>
document.write(location + "<br>");
document.write(location.search + "<br>");
document.write(decodeURIComponent(
location.search.substr(location.search.indexOf("=") + 1)
));
</script>
</body>
</html>
原理是這樣的:form 用 method="get" 送出時,瀏覽器會把 name=value 成對串接、附加在 action 的網址後面,變成 b.html?hid=123。接收頁只要讀 location.search 就能拿到這段查詢字串。
decodeURIComponent 的位置不對。原範例直接對整段 search 解碼,但其實每個值都該分別解碼。多參數時這麼做會出錯,正確寫法是逐項處理:
const params = new URLSearchParams(location.search);
const hid = params.get('hid');
console.log(hid); // "123"
用 URLSearchParams 取代字串操作。這是現代瀏覽器都支援的 API,比 indexOf + substr 簡潔可靠得多,還能處理編碼、重複鍵名、空值等邊界情況。
document.write 不該用來輸出使用者可控的資料。這段程式碼把網址內容直接寫進頁面,如果網址裡被塞入 <script>,就會形成反射型 XSS。改用 textContent:
document.getElementById('out').textContent = hid;
URL 查詢字串:GET 表單或手動拼接。優點是可書籤、可分享、可用上一頁回到前狀態;缺點是有長度上限,且資料會暴露在網址列、伺服器日誌與參照來源中。適合傳遞非敏感的識別資訊。
sessionStorage / localStorage:在同一個 origin 下跨頁面共享資料。localStorage 永久保存,sessionStorage 只在該分頁存活。適合傳遞表單草稿、多步驟流程的中間狀態。
sessionStorage.setItem('draft', JSON.stringify(data));
const data = JSON.parse(sessionStorage.getItem('draft'));
Cookies:會自動隨請求送到伺服器,適合身分識別。但容量小(約 4KB)、且每次請求都會附帶,不適合放大量資料。
後端 session:最安全的方式。前端只傳一個 session id,實際資料留在伺服器。任何敏感資料都應該走這條路。
只是傳個 id 或查詢條件,用 URL 參數;表單填到一半跳去別頁再回來,用 sessionStorage;涉及身分或隱私的資料,一律留在後端,前端只拿 session id。不要把敏感資訊放進網址列——它會被記錄在歷史紀錄、伺服器 log、以及任何第三方腳本都能讀取的地方。