2013年8月7日 星期三

Jquery can't change image refresh in Firefox and IE

1. Problem:
 Some times we try dynamic to change a picture in html,
and we assume this image is same,
in firefox and IE, this doesn't work,
and we happen is in captcha image.


2. Solution
This is because the firefox and ie seem the picture name is same, so they didn't send the request.  solution is add a random number in the request.
// HTML
<a href="" id="captcha_img_link"  title="Change img">chane</a>
<img id="captcha_img" align="middle" src="jcaptcha.jpg"  />


// Javascript
$(function (){
    // change image
    $('#captcha_img_link').click(function () {
        // Avoid the cache using appach random
        $("#captcha_img").attr('src',"./jcaptcha.jpg?random=" + Math.floor((Math.random()*20)+1));               
        return false;
    });
});




Reference:
How to force a web browser NOT to cache images

沒有留言:

張貼留言