實際專案中常常遇到這樣的需求:在子系統頁面之間跳轉,並在新視窗中打開。
我們專案組使用的是 SSH 框架,所以 URL 都是類似 ****.action 的形式,同時還帶兩個參數(系統 ID 與系統名稱)。這兩個參數被 Struts 攔截後存入 session,而在打開的子系統頁面裡,還有一個 ztree 插件實作的樹狀選單需要系統 ID 才能初始化。
問題就在這裡:直接用 window.open(url, "_blank") 把參數拼在網址上,會造成兩個困擾——URL 過長,以及參數暴露在網址列上。因此想改用 POST 方式提交,把參數藏在請求本文裡。
第一個想到的方案是 Ajax 提交,但兩個參數的傳遞會出問題:Ajax 提交與 window.open() 會讓 action 被執行兩次,因此只能放棄。
接著回頭重讀 window.open() 的文件才確認:這個方法預設就是 GET 提交,要實現 POST 必須另尋他法。
這是最常被採用的做法——程式matically 組出一個 target 指向新視窗名稱的隱藏表單,把參數放進 hidden input,然後提交它。
function openPostWindow(url, name, data1, data2) {
var tempForm = document.createElement("form");
tempForm.id = "tempForm1";
tempForm.method = "post";
tempForm.action = url;
tempForm.target = name;
var hideInput1 = document.createElement("input");
hideInput1.type = "hidden";
hideInput1.name = "xtid";
hideInput1.value = data1;
var hideInput2 = document.createElement("input");
hideInput2.type = "hidden";
hideInput2.name = "xtmc";
hideInput2.value = data2;
tempForm.appendChild(hideInput1);
tempForm.appendChild(hideInput2);
// 處理瀏覽器事件模型差異
if (document.all) {
tempForm.attachEvent("onsubmit", function() {}); // IE
} else {
tempForm.addEventListener("submit", function() {}, false); // Firefox
}
document.body.appendChild(tempForm);
if (document.all) {
tempForm.fireEvent("onsubmit");
} else {
tempForm.dispatchEvent(new Event("submit"));
}
tempForm.submit();
document.body.removeChild(tempForm);
}
openWindow() 函式,若一併啟用會多開一個 about:blank 空白頁,實作時要留意。form.submit() 的動態建立流程,其實不需要手動觸發 submit 事件;直接 appendChild 後呼叫 submit() 即可,程式碼能精簡不少。上面的 fireEvent/dispatchEvent 主要是為了解決特定環境下表單未完全就位的時序問題。