0

I am trying to render some Javascript from my controller to my GSP like this:

render text: """<script type="text/javascript">
                                            alert("Row number: " + rowNumber); 
                                        </script>""",
                               contentType: 'js'

where "rowNumber" is a variable in my Controller and I want the value of it to appear in the alert box. I can't seem to figure out the syntax and need a little help. Presently I get this error in the browser:

Uncaught ReferenceError: rowNumber is not defined 

1 Answer 1

1

You want something like this:

render text: """<script type="text/javascript">
                    alert("Row number: " + ${rowNumber}); 
                </script>""",
       contentType: 'js'

That will cause the value of rowNumber in your controller to be substituted into the string before the string is rendered.

EDIT:

(another option)

You could do away with the concatenation altogether with something like this:

render text: """<script type="text/javascript">
                    alert("Row number: ${rowNumber}"); 
                </script>""",
       contentType: 'js'
Sign up to request clarification or add additional context in comments.

3 Comments

The way you had it, the literal alert("Row number: " + rowNumber); is what would be rendered instead of something like alert("Row number: " + 42);.
All of that assumes there is a variable named rowNumber in scope where you are calling render in your controller there.
Note that you could also put the JavaScript into a template and render that from the controller rather than having to triple-quote it inline. Then you would pass rowNumber into the template, e.g., render template: 'rowNumberJS', model: [rowNumber: rowNumber]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.