沒有後端程式的靜態頁面,想在頁面之間傳值,最簡單的方式就是把參數放在網址後面(GET 風格),再用 JavaScript 從 location 裡挖出來。以下整理兩種常用寫法與一個完整實例。
var LocString = String(window.document.location.href);
function getQueryStr(str) {
var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi")
.exec(LocString), tmp;
if (tmp = rs) {
return tmp[2];
}
return ""; // 找不到參數時回傳空字串
}
// 呼叫方式
document.getElementById("user").value = getQueryStr("user");
document.getElementById("password").value = getQueryStr("password");
document.getElementById("sysno").value = getQueryStr("sysno");
正則的直覺是「以參數名開頭、抓等號後面直到 & 或結尾為止的所有字元」,好處是一次就能寫成通用函式,任意參數名都能取。
urlinfo = window.location.href; // 取得目前網址
len = urlinfo.length; // 網址長度
offset = urlinfo.indexOf("?"); // 參數串開始的位置
newsidinfo = urlinfo.substr(offset, len); // 取出 id=1 這種字串
newsids = newsidinfo.split("="); // 以 = 分割
newsid = newsids[1]; // 參數值
alert("您要傳遞的參數值是" + newsid);
這個寫法更短,但只適合「網址中確定有參數」的情況。若採用 POST 提交,網址裡不會出現參數,這招就無效了——它只對 GET 或手動附加參數的網址有用。
aa.htm(輸入端):把輸入框的值拼進網址後開新視窗。
function submit() {
var input1 = document.getElementById("inputid");
window.open("bb.htm?inputStr=" + input1.value); // 傳入參數
}
bb.htm(接收端):封裝成一個 request 物件,用 window.location.search 取值。
var request = {
QueryString : function(val) {
var uri = window.location.search;
var re = new RegExp("" + val + "=([^&?]*)", "ig");
return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
}
}
var rt = request.QueryString("inputStr");
alert(rt);
同一頁也可以一次取多個參數,並在取不到時給預設值,讓畫面不至于空白:
var a = request.QueryString("a");
var b = request.QueryString("b");
var c = request.QueryString("c");
if ((a != null)) { a = a } else { a = "參數A空" }
if ((b != null)) { b = b } else { b = "參數B空" }
if ((c != null)) { c = c } else { c = "參數C空" }
document.writeln("參數A: " + a);
document.writeln("<br>參數B: " + b);
document.writeln("<br>參數C: " + c);
網址參數是明文可見的,因此不要把密碼、身分證字號或任何敏感資料放在 query string 上,這類資訊應由 POST 搭配 HTTPS 傳輸。另外現代專案若支援度允許,直接用 new URLSearchParams(location.search).get('user') 會比手寫正則更簡潔可靠;若必須相容舊版 IE,才需要上面這種正則或 split 的土法煉鋼。