【问题标题】:how to pass a javascript var value to a Grails controller?如何将 javascript var 值传递给 Grails 控制器?
【发布时间】:2010-12-14 17:28:21
【问题描述】:

我找到了以下 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 吗?据我所知,.width 方法在所有浏览器上都能获得正确的宽度。

标签: javascript image grails window size


【解决方案1】:

如果你选择使用 jQuery,你可以编写一个控制器来返回你的图像,在你的 html 中是这样的:

<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
  }
}

以上内容完全不在我的脑海中,所以你必须填写空白:-)

黑客攻击愉快。

【讨论】:

  • 你应该明确地使用jQuery而不是滚动你自己的javascript!
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 为什么不params.fieldNameparams.int(fieldName)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多