Updating an image that is re-uploaded periodically
I have a webcam script that sends a JPG via FTP to my webserver every 10 seconds (overwriting the original).
How can I get jQuery to refresh that image? I tried:
window.onload = function() {
$('body').prepend('<img id="cam" src="ww.jpg" alt="" />');
setInterval(runAgain, 12500);
};
function runAgain() {
$.ajax(开发者_如何转开发{
url:'ww.jpg',
cache:false,
beforeSend:function() {
$('#cam').remove();
},
success:function() {
$('body').prepend('<img id="cam" src="ww.jpg" alt="" />');
}
});
}
Note: I don't want to refresh the page if I can help it.
A dirty way is appending a timestamp or a random number at the end of the image src, to prevent the caching, like img src="image.jpg?random=[RANDOM]" where [RANDOM] is the timestamp or the random number
It looks like you have the problem with the caching - browser already has the image in the cache and doesn't load it again from server. The simplest way is to add the random parameter that will make the browser think that it is the other image:
...
url:'ww.jpg?' + Math.random()
...
It is possible to achieve the same effect with serverside tune-ups, but this way is probably least intrusive and easier to implement.
You actually only need to refresh the src
. Of course you should use a cache buster to avoid browser caching the image destonation. A solution in this case would be random query string parameter.
$(function() {
var $img = $('<img>', {
src: 'ww.jpg'
}).appendTo(document.body);
setInterval(function() {
$img.attr('src', function(_, src) {
return [src, '?', ~~(Math.random() * 40000)].join('');
});
}, 12500);
});
function updateLogo() {
var base_src = "http://www.google.com/logos/2011/graham11-hp-start.png";
var logo = $('#logo');
var timestamp = new Date().getTime();
// uncomment the timestamp part if your server supports an extra parameter to prevent caching
logo.attr('src', base_src);// + '?_ts=' + timestamp);
};
setInterval(updateLogo, 1000);
If your server supports an extra parameter in the image URL you'll prevent caching the image.
精彩评论