[英]Reload php image (captcha)
这是一个带有验证码的验证码图片,如果用户需要,该链接将重新加载图片。 此代码仅在Google Chrome中有效。 如何使其在其他浏览器中起作用?
<img id="captcha" src="captcha.php">
<a id='reload'>Refresh now</a>
$('#reload').click(function(){
$('#captcha').attr('src','captcha.php')
})
其他浏览器可能会缓存图像。 请尝试以下操作:
$("#captcha").attr("src", "captcha.php?"+(new Date()).getTime());
尝试不使用缓存方法(顺便说一句,需要设置标签href属性):
<a id='reload' href='#'>Refresh now</a>
$('#reload').click(function(){
var timestamp = new Date().getTime();
$('#captcha').attr('src','captcha.php?'+timestamp)
})
可能是浏览器缓存。 换句话说,浏览器看到它已经加载了captcha.php
因此不需要再次加载它。
尝试将查询字符串追加到包含当前时间的图像源。 由于图像源现在将是浏览器尚未加载的URL,因此它将尝试重新加载它。
<img id="captcha" src="captcha.php">
<a id='reload'>Refresh now</a>
$('#reload').click(function(){
$('#captcha').attr('src','captcha.php?' + (new Date()).getTime());
});
更好的是,在captcha.php
上设置HTTP标头,以确保浏览器不会缓存它。
<?php
// Set headers to NOT cache a page
header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
header("Pragma: no-cache"); //HTTP 1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
尝试这个:
DOM
<div id="captcha-container">
<img src="captcha.php" id="captcha">
</div>
jQuery的
$('#reload').click(function() {
$('#captcha').remove();
$('#captcha-container').html('<img src="captcha.php" id="captcha">');
});
NET日志
每次单击“重新加载”,都会发出一个新请求。
GET captcha.php
200 OK
127.0.0.1:80
GET captcha.php
200 OK
127.0.0.1:80
GET captcha.php
200 OK
127.0.0.1:80
添加新的img元素将导致浏览器重新加载它。
由于到目前为止所有答案都使用jQuery ,所以我想我会发布仅使用纯Javascript的代码。
// Helper function to attach event listener functions to HTML elements.
function attach(el, event, fun) {
if (el.addEventListener) {
el.addEventListener(event, fun);
}
else {
el.attachEvent("on"+event, fun);
}
}
// Find the <a id='reload'> element.
var id_reload = document.getElementById("reload");
if (null !== id_reload) {
// Find the <img id='captcha'> element. We assume this works, so no check against null.
var id_captcha = document.getElementById("captcha");
attach(id_reload, "click", function() {
id_captcha.src = "captcha.php?" + (new Date()).getTime();
});
}
如果图像的src保持不变,则浏览器将不会向服务器发送新的HTTP请求。 因此,通过添加无用的时间戳来更改src。
在浏览器javascript中:
var capImage = document.getElementById("captcha-image");
capImage.addEventListener("click", function () {
capImage.src = "/captcha?timestamp=" + (new Date()).getTime();
});
这是刷新验证码图像的演示。
您还需要删除时间戳记,因为它将始终与先前的源URL连接在一起。 当用户多次单击重新加载按钮时,您可能会遇到问题。 因此,最好在附加新时间戳之前从URL中删除先前的时间戳。
$('#reload').on('click', function(){
var img=$('#captchaimage');
var src=img.attr('src');
var i=src.indexOf('?dummy=');
src=i!=-1?src.substring(0,i):src;
d = new Date();
img.attr('src',src+'?dummy='+d.getTime());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.