admin管理员组

文章数量:1327683

How can I reload this image to get the new one from the server, using javascript without needing to reload the page?

<img src="?option=_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" />

Thank you

How can I reload this image to get the new one from the server, using javascript without needing to reload the page?

<img src="?option=_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" />

Thank you

Share edited May 2, 2013 at 8:20 themhz asked May 2, 2013 at 8:03 themhzthemhz 8,42422 gold badges85 silver badges109 bronze badges 2
  • 2 Have you considered Googling javascript reload image? – Pekka Commented May 2, 2013 at 8:03
  • Yes but those examples look like they are cashing my image. probably I need to reset the rand in javascript now – themhz Commented May 2, 2013 at 8:07
Add a ment  | 

3 Answers 3

Reset to default 2

This should do it:

thatImgObj.src = thatImgObj.src.replace(/&r=\d+/, "&r="+ ~~(Math.random()*1e7));

(Of course, with a chance of 1e-7 to getting the same cachebreaker again - a timestamp might be a better option)

Well the simplest way I think would be changing the src attribute in Javascript. So like: YouImageElement.src += "&rand2"+Math.random();

Modifying the src attribute would cause the reload of the image and because it has another random number set Client Side, it shouldn't be cached.

Your code

Added id="img1"

<img id="img1" src="?option=_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" />

JS Code:

var newImage = new Image();
newImage.src = document.getElementById("img1").src + "&_=" + new Date().getTime();

Added a cachebreaker at the end of the url

本文标签: jqueryHow to reload image using javascriptStack Overflow