Dynamically refreshing an image using ajax within Grails
I have a web page where I need periodically update image based on several conditions. For now I'm using this:
<html>
<head>
<meta http-equiv="refresh" content="3">
</head>
<body>
<img src="${createLink(controller:'advertisment',action:'viewImage',id:advertismentInstance.id)}"/>
</body>
</html>
But it causes total reload of the web page, so I want it to be done with Ajax (I'm also using Prototype framework which is default in Grails).
Provide with advertisment controller method:
def viewImage = {
log.info("before view Image")
def adv = Advertisment.get(params.id)
byte[] image = adv.fileContent
response.outputStream << image
log.info("after view Image")
}
device controller method:
def showAdv =
{
log.info("showAdv start")
def deviceInstance = Device.get(params.id)
int totalNumberOfAdv = deviceInstance.advertisment.size();
Random rand = new Random()
int advToShow = rand.nextInt(totalNumberOfAdv+1) - 1;
def advertismentInstance = deviceInstance.advertisment.toArray()[advToShow]
if(advertismentInstance)
{
render(view: "image", model: [deviceInstance :deviceInstance,advertismentInstance: advertismentInstance])
}
else
{
flash.message = "${message(code: 'default.no开发者_如何学编程t.found.message', args: [message(code: 'advertisment.label', default: 'Advertisment'), params.id])}"
}
log.info("showAdv end")
}
Give your
<img/>
an id:<img id="foo" src="..."/><!-- keep the existing src -->
Remove the
<meta/>
that's refreshing the page.Before the closing
</body>
tag, add this:<script> var img = document.getElementById('foo'); // id of image setInterval(function() { var stamp = new Date().getTime(); img.setAttribute('src', img.getAttribute('src') + '?_=' + stamp); }, 3000); </script>
Update your
viewImage
action to actually do the randomization before rendering the image. This probably means combining parts ofshowAdv
intoviewImage
.
精彩评论