2010-12-14 11 views
3

ブラウザのウィンドウサイズを取得するために、次のjavascriptコードが見つかりました。Grailsコントローラにjavascriptのvar値を渡す方法は?

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

がどのように私はそうすることができます。

使用して構築されていますか? ありがとうございます!

+1

jQueryの使用を検討しましたか?私が知る限り、['.width'](http://api.jquery.com/width/)メソッドはすべてのブラウザで正しい幅を取得します。 – treeface

答えて

0

createLinkタグでは、コントローラーアクションの呼び出しでパラメーターを渡すことができます。 JavaScriptを使って値を決定し、それをcreateLinkタグで参照できる隠し変数に差し込みます。 jQueryには、DOM要素に簡単にアクセスするためのいくつかの素晴らしいオプションがあります。

たとえば、あなたのimg要素は次のようになります。<img src="${createLink(controller:'chart', action:'buildChart', params:\"['vpWidth' : document.getElementById(\'vpWidth\').value, 'vpHeight': document.getElementById(\'vpHeight\').value]\")}" />

は、我々はremoteFunction方法は、GrailsとjQueryを使って呼び出しを構築するために同様の技術を使用しています。上の例を調整しなければならないかもしれませんが、それはテストされていません。

0

javascriptを使用して、必要な数字を含む隠しフォームフィールドを追加します。 with with the grails controlerでは、request.getParameter( "fieldName")を使用して文字列の形式で値を取得し、次にintに変換してサイズを変更します。

+0

なぜ 'params.fieldName'や' params.int(fieldName) 'はありませんか? –

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

上記は完全に私の頭の上から外れているので、空白を記入する必要があります:-)

ハッピーハッキング。

+0

あなたは自分のjavascriptを動かす代わりに、間違いなくjQueryを使うべきです! – sbglasius

関連する問題