Sending JSON to javascript on GSP
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>
The encodeAsJSON()
method works well for outputting JSON data into JavaScript:
Controller
def testData() {
def data = [name: "Sales", values: [5, 20, 45]]
[data: data]
}
View (GSP)
<script>
var data1 = ${raw(data)}; //{name=Sales, values=[5, 20, 45]}
var data2 = ${raw(data as grails.converters.JSON)}; //{"name":"Sales...
var data3 = ${data.encodeAsJSON()}; //{"name":"Sales","values":[5,20,45]} CORRECT!
</script>
Using raw()
on a Groovy object does not produce JavaScript compatible output (see data1
), and using it after the JSON converter results in unwanted "
encoding (see data2
). Using encodeAsJSON()
produces the correct output (see data3
).
Documentation:
http://grails.org/doc/latest/guide/security.html#codecs
Update:
I've switched to using a taglib with:
out << "<script>const data = " + raw((data as JSON) as String) + ";</script>"
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>