ajax - 在Grails中使用Ajax动态刷新图像

我有一个网页,需要定期更新基于
在几种情况下。现在,我正在使用此:

 <html>
   <head>
   <meta http-equiv="refresh" content="3">
   </head>
    <body>
        <img src="${createLink(controller:'advertisment',action:'viewImage',id:advertismentInstance.id)}"/>
    </body>
</html>

但这会导致网页的重新加载,所以我希望这样做
与Ajax一起使用(我也使用了Prototype框架,这在Grails中是默认的)。

提供广告 Controller 方法:
 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")
    }

设备 Controller 方法:
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.not.found.message', args: [message(code: 'advertisment.label', default: 'Advertisment'), params.id])}"
        }

        log.info("showAdv end")

    }

最佳答案

  • 给您的<img/>一个ID:
    <img id="foo" src="..."/><!-- keep the existing src -->
    
  • 删除刷新页面的<meta/>
  • 在结束</body>标记之前,添加以下内容:
    <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>
    
  • 更新您的viewImage操作以在渲染图像之前实际进行随机化。这可能意味着将showAdv的一部分合并为viewImage
  • https://stackoverflow.com/questions/7560652/

    相关文章:

    hibernate - Grails渴望通过滚动获取

    grails - grails控制列表方法的外观

    grails - jQuery移动样式适用于整个项目-为什么?

    inheritance - Grails/GORM:继承的域类的行为不一致(测试VS Bootstr

    grails - 使用 resources.groovy 定义服务

    shell - 在每行的开头添加文本

    ruby-on-rails - Rails 4.1:Rails:Module的未定义方法 `appl

    command-line - SSH与FTP:通过终端将本地文件推送到服务器

    image - Grails-从 Controller 加载图像

    grails - 由于模糊的def递归导致的grails中的堆栈溢出