Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - Dynamic image refresh

How would I go about updating an image that gets updated on a server every couple of seconds with out the user having to hit the refresh button, my first guess was ajax but I haven't really worked with it before. Could someone point me in the right direction?

EDIT: Forgot to mention that the image is a .gif generated by a perl script - trying to get it from url returns the script itself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...