window.open 默認發起 GET 請求。需 POST 傳參時,在新窗口動態創建 <form method="post"> 並自動提交。
function openNewPageWithPostData(url, target, paramNames, paramValues) {
var win = window.open('', target); // 先打開空白窗口
if (!win) return false; // 被攔截
var html = '<html><head></head><body>';
html += '<form id="postForm" method="post" action="' + url + '">';
if (paramNames && paramValues && paramNames.length === paramValues.length) {
for (var i = 0; i < paramNames.length; i++) {
html += '<input type="hidden" name="' + paramNames[i]
+ '" value="' + paramValues[i] + '" />';
}
}
html += '</form>';
html += '<script>document.getElementById("postForm").submit()</script>';
html += '</body></html>';
win.document.write(html);
win.document.close(); // 重要:關閉文檔流
return win;
}
openNewPageWithPostData(
'/report/export',
'_blank',
['userId', 'dateRange', 'format'],
[12345, '2024-01', 'excel']
);
window.open('') 可能被瀏覽器攔截,需用戶交互觸發(點擊事件中調用)encodeURIComponent 轉義,防止注入腳本document// 1. 隱藏表單提交(同窗口)
const form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.target = '_blank';
params.forEach((v, k) => {
const input = document.createElement('input');
input.type = 'hidden'; input.name = k; input.value = v;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
form.remove();
// 2. fetch + blob 下載(文件導出場景)
fetch(url, {method: 'POST', body: JSON.stringify(data)})
.then(r => r.blob())
.then(blob => { /* 創建下載鏈接 */ });
隱藏表單法無彈窗攔截風險,體驗更好;文件導出場景推薦 fetch+blob。