Sending JSON to javascript on GSP
The problem is that the JSON is being encoded as HTML. Try the following instead:
Controller
def testData() { def result = [:] result['name'] = "Sales" result['type'] = "bar" result['data'] = [5, 20, 45, 10, 10, 20] [data: result as JSON]}
GSP
<script> var data = ${raw(data)};</script>
You don't need $(document).ready
because the JS code
var data = ${raw(data)};
is generated on the server-side
Working solution :
def action() { [data: data as JSON]}
GSP page:
<g:applyCodec encodeAs="none"> var data = ${data};</g:applyCodec>
The following worked for me using Grails 2.4.3:
Controller:
def result = [:]result['type'] = "bar"result['data'] = [5, 20, 45]model: [data: result as JSON]
GSP:
<script>// this worked!var data = ${raw(data as String)};</script>
Produced desired result:
<script>// this worked!var data = {"type":"bar","data":[5,20,45]};</script>
The accepted answer by Dónal DID NOT work for me:
Controller (same as my working example above)
GSP (did NOT work):
<script>// did NOT work!!var data = ${raw(data)};</script>
Produced same bad result:
<script>// did NOT work!!var data = {"type":"bar","data":[5,20,45]};</script>