微信內嵌 H5 頁面:「我的個人中心」→ 點擊「填寫認證」→ 新頁面提交成功 → 用戶點擊左上角返回 → 原頁面需刷新認證狀態為「認證中」。
原代碼使用 $.ajax({ method: 'GET', ... }),現象:
onload 觸發 AJAX200 OK 但 Response 為上一次緩存內容Cache-Control、ETag、Last-Modified)window.onload = function() {
if (needRefresh) {
$.ajax({
url: "/isAuthenticing",
type: "POST", // 關鍵:POST 不會被緩存
data: { userid: getUserId() },
cache: false, // jQuery 會自動加 _=timestamp 參數
headers: { "X-Requested-With": "XMLHttpRequest" },
success: function(res) {
if (res.result === '1') $('#approveadd a').html("+認證中");
}
});
}
};
@PostMapping("/isAuthenticing")
@ResponseBody
public Map checkAuth(@RequestParam String userid) {
// 業務邏輯
return Map.of("result", "1");
}
同步加上響應頭防緩存:
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
window.addEventListener('pageshow', function(e) {
// persisted 為 true 表示從 BFCache 恢復
if (e.persisted || sessionStorage.getItem('needRefresh')) {
sessionStorage.removeItem('needRefresh');
refreshAuthStatus(); // 發起 POST AJAX
}
});
// 離開頁面前標記
window.addEventListener('pagehide', function() {
sessionStorage.setItem('needRefresh', '1');
});
此方案兼容 iOS Safari BFCache、Android WebView、微信 WebView 等各種返回場景。
| 方案 | 優點 | 缺點 |
|---|---|---|
| GET + 隨機參數 | 改動最小 | 仍可能被代理緩存,不符合 REST 語義 |
| POST + cache:false | 語義正確、天然防緩存 | 需後端改 @PostMapping |
| pageshow + SessionStorage | 覆蓋所有返回場景、無需業務區分 | 邏輯稍複雜 |
推薦:POST + pageshow 雙重保險,徹底解決微信 H5 返回刷新難題。