[英]How to pass a value directly from a controller to a javascript file in 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.