No AJAX is necessary, just update the image's src
property. But, since it has the same url, you have to give the browser a unique address to ensure you don't just load the old image from the browser's cache. You can guarantee a unique image by getting the current date's serial number via new Date().valueOf()
and appending that to the url as a querystring.
$("#dynamicImage").prop("src", "dynamicImage.jpg?" + new Date().valueOf());
You can also use new Date().getTime()
to get the serial number, or just coerce the date to a number: +new Date()
To do it on a timer use setInterval()
. This would be the complete code that you could just drop inside a script tag in your page's <head>
:
$(function() {
var intervalMS = 5000; // 5 seconds
setInterval(function() {
$("#dynamicImage").prop("src", "dynamicImage.jpg?" + +new Date());
}, intervalMS);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…