How to pass javascript var value to Grails controller?

I found the following javascript code to get the browser window size and it works great!

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

Now I need to pass it to the Grails controller so that I can resize the image to fit the screen size.

which is built using:

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

How can i do this? Thanks in advance!

+3
source share
3 answers

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

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

, : -)

.

+1

Use javascript to add hidden form fields containing the numbers you need. From with in the grails controler uses request.getParameter ("fieldName") to retrieve values ​​in the form of a string, then converts to int and resizes.

0
source

Source: https://habr.com/ru/post/1780258/


All Articles