點擊「換一張」驗證碼圖片,Chrome/Firefox 正常更新,IE 圖片不變。
IE 默認啟用積極緩存策略:同一 URL 請求直接返回緩存,不發送網絡請求。驗證碼 URL 未變(如 /captcha),IE 認為資源未變,直接讀取緩存。
<img id="captcha" src="/captcha" alt="驗證碼" style="cursor:pointer" />
<script>
$('#captcha').click(function() {
var timestamp = Date.now(); // 或 Math.random()
this.src = '/captcha?' + timestamp; // 強制瀏覽器視為新資源
});
</script>
function changeimg() {
var time = Math.round(Math.random() * 999) + 3000; // 生成 3000-3999 隨機數
$('#captcha').attr('src', '__APP__/Public/verify/time/' + time);
}
邏輯正確:每次點擊生成新參數,URL 變化,繞過緩存。time 變量名建議改為 timestamp 或 rand 語義更清晰。
var loading = false;
$('#captcha').click(function() {
if (loading) return;
var $img = $(this);
loading = true;
$img.css('opacity', 0.5);
var newSrc = '/captcha?' + Date.now();
// 預加載新圖,加載完成再切換 src,避免閃爍
var tempImg = new Image();
tempImg.onload = function() {
$img.attr('src', newSrc).css('opacity', 1);
loading = false;
};
tempImg.onerror = function() {
alert('驗證碼加載失敗,請重試');
$img.css('opacity', 1);
loading = false;
};
tempImg.src = newSrc;
});
// 後端響應頭(以 PHP 為例)
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
雙重保障:前端隨機參數 + 後端禁緩存頭,徹底解決所有瀏覽器緩存問題。
async function refreshCaptcha() {
const res = await fetch('/captcha?' + Date.now(), { cache: 'no-store' });
const blob = await res.blob();
document.getElementById('captcha').src = URL.createObjectURL(blob);
}
cache: 'no-store' 明確指示瀏覽器不緩存,配合隨機參數雙重保險。