[英]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.