在 Web 開發中,IE 瀏覽器對 AJAX GET 請求的積極緩存機制常導致開發者遇到「請求返回上一次結果」的困擾。本文分析根因並提供多種實戰解決方案。
在請求 URL 後添加時間戳或隨機數,強制瀏覽器視為新請求:
// 方案 A:Math.random()
url + "&t=" + Math.random();
// 方案 B:時間戳(推薦,可讀性更好)
url + "?timestamp=" + new Date().getTime();
$.ajax({
type: "POST",
async: false, // 同步模式(視業務需要)
cache: false, // 關鍵:自動附加 _={timestamp} 參數
url: targetUrl,
data: postData,
success: function(data) {
// 處理回調
}
});
設置 cache: false 後,jQuery 會自動在 URL 末尾添加 _={timestamp} 參數,徹底繞過瀏覽器緩存。
cache: false,代碼侵入性最小且語義清晰。Cache-Control: no-cache, no-store, must-revalidate 從源頭禁止緩存。