简体   繁体   中英

How to reload image using javascript

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=com_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" />

Thank you

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=com_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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM