1

From my Controller i am passing a parameter to the view.

When i print the parameter from the Body it gets printed correctly. However, if i try to print the parameter from a Javascript function it doesn't work.

How can i correct this ?

Controller

def showpeople(Long id){
        def pInstance = People.get(id)
        render (view: "showpeople",model: [pInstance: pInstance])

    }

View

<script>
$(document).ready(function(){ 
var str = ${pInstance.stringval}; // <--- DOESN'T WORK  
alert (str); // <--- DOESN'T SHOW ALERT  

)}
</script>

<body>
${pInstance.stringval} <--- PRINTS SUCCESSFULLy 
</body>
1
  • var str = '${pInstance.stringval}'; If it's a string you need to wrap it in quotes of some sort or the javascript will choke on it. Commented Oct 7, 2014 at 17:34

1 Answer 1

2

The reason why your alert doesn't show is you are outputting that value as a constant instead of a valid String within javascript. You really need to wrap it in quotes and you should also encode the string value for use with javascript.

For example:

var str = '${pInstance.stringval?.encodeAsJavaScript()}';
alert(str);
Sign up to request clarification or add additional context in comments.

Comments

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.