在 Web 開發中,有時需要將較長的參數以 POST 方式傳送給伺服器,並將回應內容顯示在新視窗中。直接使用 window.open(url) 僅支援 GET 請求,且 URL 長度有限制。本文介紹兩種常見的解決方案。
window.open("about:blank")先以 AJAX 發送 POST 請求,成功後開啟空白視窗並寫入回應內容。
$.ajax({
type: "POST",
url: "${contextPath}/analyse/detail.do",
data: { carNum: carNum, ids: refIds },
success: function(str_response) {
var newWin = window.open("about:blank");
newWin.document.write(str_response);
}
});
window.open,導致使用者體驗不佳。<form> 表單提交(推薦)利用 JavaScript 動態建立一個隱藏表單,設定 target="_blank" 並提交,完美繞過攔截器。
function postToNewWindow(url, params) {
const form = document.createElement("form");
form.action = url;
form.method = "POST";
form.target = "_blank"; // 關鍵:在新視窗開啟回應
form.style.display = "none";
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
const input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = params[key];
form.appendChild(input);
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form); // 提交後清理
}
// 使用範例
postToNewWindow("${contextPath}/analyse/detail.do", {
carNum: carNum,
ids: refIds
});
若需支援 multipart/form-data(如檔案上傳),可調整表單編碼類型:
function postFormData(url, fields, files) {
const form = document.createElement("form");
form.action = url;
form.method = "POST";
form.target = "_blank";
form.enctype = "multipart/form-data";
form.style.display = "none";
// 一般欄位
for (const [key, value] of Object.entries(fields)) {
const input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = value;
form.appendChild(input);
}
// 檔案欄位(需為 FileList 或 File 陣列)
for (const [key, fileList] of Object.entries(files)) {
for (const file of fileList) {
const input = document.createElement("input");
input.type = "file";
input.name = key;
// 注意:動態建立的 file input 無法直接設定 value,
// 實際專案中建議使用 FormData 配合 fetch/XHR 處理檔案上傳。
form.appendChild(input);
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
對於單純的 POST 參數傳遞並開啟新視窗,動態建立表單提交 是最穩健、相容性最高的方案。它避開了瀏覽器彈窗攔截機制,且程式碼簡潔易維護。建議在專案中封裝成通用工具函式,方便複用。