作者:羅代均。轉載請保持完整性。
大家有沒有發現,有些網頁在重新整理時會跳出一個提示視窗,按「確定」才會真的刷新;而有些頁面不會提示,直接就刷新了。
差別在表單的 method:如果頁面沒有 form,不會彈出提示視窗;如果有 form 且 method="post",會彈出提示;若是 method="get",則不會彈出。
原因是 POST 被視為「有副作用的請求」——理論上重新送出可能重複建立訂單或重複扣款,因此瀏覽器要求使用者確認。GET 則被視為無副作用,可以直接重送。
window.location.reload():重新整理目前頁面。
若是用 window.open() 彈出的視窗要刷新父視窗:window.opener.location.reload()。
若是用 window.showDialog 彈出的模態視窗:window.dialogArguments.location.reload()。
下面給兩個讓視窗在螢幕中央開啟的例子。
window.open() 方式
function ShowDialog(url) {
var iWidth = 300; // 視窗寬度
var iHeight = 200; // 視窗高度
var iTop = (window.screen.height - iHeight) / 2;
var iLeft = (window.screen.width - iWidth) / 2;
window.open(url, "Detail",
"Scrollbars=no, Toolbar=no, Location=no, Direction=no, Resizeable=no," +
"Width=" + iWidth + ", Height=" + iHeight + ", top=" + iTop + ", left=" + iLeft);
}
window.showModalDialog 方式
function ShowDialog(url) {
var iWidth = 300;
var iHeight = 200;
var iTop = (window.screen.height - iHeight) / 2;
var iLeft = (window.screen.width - iWidth) / 2;
window.showModalDialog(url, window,
"dialogHeight: " + iHeight + "px; dialogWidth: " + iWidth + "px;" +
"dialogTop: " + iTop + "; dialogLeft: " + iLeft + ";" +
"resizable: no; status: no; scroll: no");
}
注意這裡的第二個參數是 window,它會成為模態視窗中的 dialogArguments,讓子視窗得以存取父視窗。
在 JSP 頁面中加入下列語句以停用快取:
<%
response.setHeader("Pragma", "No-Cache");
response.setHeader("Cache-Control", "No-Cache");
response.setHeader("Expires", "0");
%>
這三個標頭需要一起下:實務上還應加上 Cache-Control: no-store, must-revalidate,並在 HTML 中補上對應的 meta http-equiv,因為部分舊版瀏覽器與代理伺服器會各自採用不同的判斷依據。
上面兩種開視窗的方式,含義完全不同,值得分清楚:
window.open 開的是獨立視窗,兩頁之間以 opener 相互參照。今天若需要新分頁,請用 <a target="_blank" rel="noopener">;noopener 會切斷 window.opener,避免新頁面反向操作你的頁面,這已是安全上的基本要求。
showModalDialog 則已被標準廢除並從主流瀏覽器移除,請改用 <dialog> 搭配 showModal(),它同樣能拿到使用者回傳的結果(透過 returnValue),而且不会被任何彈出視窗攔截機制影響。
至於「重新整理 POST 頁面跳提示」這件事,它是瀏覽器正確的行為,不該試圖繞過。若你希望重新整理後不會重複送出,正確的做法是 Post/Redirect/Get 模式:處理完 POST 之後回傳 302 導向到結果頁,讓瀏覽器的最後一次請求是 GET。