3

My problem is passing Map object from grails controller to JavaScript. I have the following code inside controller

def scoreValue=new HashMap<String,String>();
scoreValue.put("0","poor");
scoreValue.put("1","good");
...

return (view:'viewname',model:[scoreValue:scoreValue]);

I have been searching for solution and have got this link pass a groovy array to javascript code. but could not help.

What I did was change the return statement to

return (view:'viewname',model:[scoreValue:scoreValue as grails.converters.JSON]) and inside gsp view I have the following code.

<g:if test="${scoreValue}">
     var scoreValue=${scoreValue};
</g:if>

But what i got inside html page is the following

 var scoreValue={&quot;0&quot;:&quot;Failure&quot;,&quot;1&quot;:&quot;Poor&quot;}

any help would be appreciated. thanks!

2 Answers 2

2

There's actually a few ways of handling GSP encoding. In addition to D. Kossatz's answer, these methods will help you out (see more at mrhaki's excellent Grails Goodness blog)

 var scoreValue=${raw(scoreValue)};

 var scoreValue=${scoreValue.encodeAsRaw()}

Please be aware that there is an inherent risk of cross-site scripting vulnerabilities when rendering user input unprotected on the page. So long as you know for certain that only you can set that value, and proper safe-checks to ensure it is what it is supposed to be, you should be fine.

Sign up to request clarification or add additional context in comments.

1 Comment

when i did as you said i got var scoreValue= {0=poor, 1=good} . and showing error because it is considering good and poor as variables not strings.
1

Try:

var scoreValue= <g:applyCodec encodeAs="none">${scoreValue}</g:applyCodec>;

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.