1

I have checked a lot of forums, but I haven't got my answer. So - I have a lot of JS code, so i keep it in separate .js file (not in .gsp view). But now I have problems of accessing controller mapped values - I need them at my JS page, so I could generate my game field (based on values, that controller gives. I have

def createGame(long id) {
 //getting my game info object...
 [gameInfo:gameInfo]      
}

And then I accessed them in view, like - ${gameInfo.playerName} etc. But how to get them to JS file? For example, player has chosen an object's color (that is JS generated). One of examples could be ball.fillStyle(${gameInfo.ballColor}) But that, of course, is not working! Thanks in advance! :)

1 Answer 1

3

You have to assign the values using inline JavaScript.

<script type="text/javascript">
 var gameInfo = ${gameInfo as JSON};
</script>
3
  • Am I putting this into my .gsp file? And how to access it's values? like - gameInfo.playerName?!
    – Mike B
    Commented Jul 23, 2013 at 14:55
  • Yes, it will be in your GSP. Access it like your normally would. It's a JavaScript object when you do "as JSON". If you don't understand JavaScript objects, you need to do some reading. Commented Jul 23, 2013 at 15:39
  • 2
    This didn't work for me in Grails v2.3.11 - the quotes around string values were escaped even when I tried ${raw(foo as JSON)}. I ended up using this instead: var gameInfo = ${gameInfo.encodeAsJson()};. EDIT: my variable was a Map.
    – nickdos
    Commented Dec 2, 2014 at 3:01

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.