繁体   English   中英

如何将javascript var值传递给Grails控制器?

[英]how to pass a javascript var value to a Grails controller?

我找到了以下javascript代码来获取浏览器窗口大小,它工作得很好!

<script type="text/javascript">
<!--

 var viewportwidth;
 var viewportheight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
    && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }

 // older versions of IE
 else
 {
       viewportwidth = document.body.clientWidth,
       viewportheight = document.body.clientHeight
 }
document.write('<p>Your viewport width is <b>'+viewportwidth+'x'+viewportheight+'</b>.</p>');
//-->
</script>

现在我需要将它传递给Grails控制器,这样我就可以根据屏幕大小调整图像大小。

使用以下内容构建:

<div align="center" valign="middle">
<img src="${createLink(controller:'chart', action:'buildChart')}" />
</div>

我怎么能这样做? 提前致谢!

如果您选择使用jQuery,您可以编写一个返回您的图像的控制器,如下所示:

<img id="picture"/>
....
....
<g:javascript>
    // Load something when DOM is fully loaded
    $(document).ready(function() {
       var width = $(window).width()
       var height = $(window).height()
       $('img#picture').attr('src','${createLink(controller: 'image', action: 'resize')}?width='+width+'&height='+height)
   })
</g:javascript>
....
</body>

还有一些控制器代码:

class ImageController {

  def resize = {
     def width = params.int('width')
     def height = params.int('height')
     // ... resize your image and return your image in the output stream
  }
}

以上完全脱离了我的头脑,所以你必须填补空白:-)

快乐的黑客。

使用javascript添加包含所需数字的隐藏表单字段。 从grails控制器中使用request.getParameter(“fieldName”)以字符串形式检索值然后转换为int并进行调整大小。

createLink标记将允许params在该调用上传递给控制器​​操作。 让您的javascript确定值,然后将它们插入可由createLink标记引用的隐藏变量中。 jQuery有一些很好的选项可以轻松访问DOM元素。

例如,你的img元素可能如下所示: <img src="${createLink(controller:'chart', action:'buildChart', params:\\"['vpWidth' : document.getElementById(\\'vpWidth\\').value, 'vpHeight': document.getElementById(\\'vpHeight\\').value]\\")}" />

我们使用类似的技术来构建使用Grails和jQuery的remoteFunction方法调用。 您可能需要调整上面的示例,它是未经测试的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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