[英]How to reload an image using ajax
这是我的captcha.php脚本:(它创建了一个图像)
// creating a image in this script and set its value on the session
此外,我在contact_us.php文件中有一个<img>
用于显示验证码图像:
<img src="http://localhost/captcha.php" class="captcha_pic" alt="Captcha">
此外,我有一个 ajax 代码用于在contact_us.js 中提交该表单(此文件已附加到 contact_us.php) :
$("#f_contact_form").on("submit", function (e) {
e.preventDefault(e);
$.ajax({
url: $("#f_contact_form").attr("action"),
type: 'POST',
data: $("#f_contact_form").serialize(),
dataType : 'JSON',
success: function (contact) {
$(".contact_message").html(contact.message);
// here I need to reload that image url for changing the captcha image
}
});
});
应该注意的是,当我使用[inspect element] (在静态中)更改该图像的 url 然后我写了正确的名称时,图像将被更改。 例如,我用src=".../captcha.ph"
替换当前图像 url,然后我写了正确的名称src=".../captcha.php"
,然后页面将被更改(正是我想要的)。
现在有任何重新加载验证码图像的解决方案吗?
您需要使用附加的唯一查询字符串重新加载图像,以防止浏览器缓存图像。 最简单的方法是附加当前时间。 由于您已经在使用 jQuery,因此您可以使用以下一种方法。
var unique = $.now();
$('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + unique);
但是,有些人可能会反对此解决方案,因为它会填满您的缓存。 尽管替代方案将要求您发送缓存控制标头。
那里有很多解决方案。 以下是您的一些选择。
删除您的图像,然后创建一个新图像。
$("#images").remove(); $("div").html("<img src='http://localhost/captcha.php' class='captcha_pic' alt='Captcha'>")
使用 unique 避免缓存。
$("#f_contact_form").on("submit", function (e) { e.preventDefault(e); $.ajax({ url: $("#f_contact_form").attr("action"), type: 'POST', data: $("#f_contact_form").serialize(), dataType : 'JSON', success: function (contact) { $(".contact_message").html(contact.message); $('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + new Date().getTime()); } }); });
$.now()在 jQuery 3.3 中已被弃用。 基于接受的答案的正确方法:
var unique = Date.now();
$('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + unique);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.