开发者

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")

    }


  1. Give your <img/> an id:

    <img id="foo" src="..."/><!-- keep the existing src -->
    
  2. Remove the <meta/> that's refreshing the page.

  3. 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>
    
  4. Update your viewImage action to actually do the randomization before rendering the image. This probably means combining parts of showAdv into viewImage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜