在GSP上发送JSON到JavaScript [英] Sending JSON to javascript on GSP
问题描述
def testData(){
def result = [:]
结果['name'] =销售额
结果['type'] =bar
结果['data'] = [5 ,20,45,10,10,20]
[data:result as JSON]
}
在testData.gsp中,我想在JavaScript中获取JSON对象:
< script> ;
$(document).ready(function(){
var data = JSON.parse($ {data});
})
< / script>
然后我得到一个异常:
未捕获的SyntaxError:意外的令牌{
p>
var data = JSON.parse({& quot; name& quot;& quot; Sales& quot;& QUOT;类型&安培; QUOT;:&安培; QUOT;栏&安培; QUOT;,&安培; QUOT;数据&安培; QUOT;:5,20,45,10,10,20]});
它看起来像JSON搞砸了。我认为它曾经以这种方式工作。也许这是新的Grails?我怎样才能解决这个问题?谢谢。
更新:
问题已解决。请参阅接受的答案中的评论。
Update2:
当我今天检查应用程序时,它再次失败。我做了原始方法所需的文档,但没有运气。解决方法是使用每页编码。这一个我测试彻底。它确实有效。
问题在于JSON被编码为HTML。请尝试以下内容:
控制器
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>
您不需要 $(document).ready $ c因为JS代码
var data = $ {raw(data)};在服务器端生成
I'm using Grails 2.3.7 and I have a controller action as follows:
def testData(){
def result = [:]
result['name'] = "Sales"
result['type'] = "bar"
result['data'] = [5, 20, 45, 10, 10, 20]
[data: result as JSON]
}
In the testData.gsp I'd like to get the JSON object in javascript:
<script>
$(document).ready(function(){
var data = JSON.parse(${data});
})
</script>
Then I got an exception:
Uncaught SyntaxError: Unexpected token {
on the line:
var data = JSON.parse({"name":"Sales","type":"bar","data":[5,20,45,10,10,20]});
It looks like JSON is messed up. I think it used to work this way. Maybe it's new Grails? How can I fix this? Thanks.
Update: Problem solved. See the comments in the accepted answer.
Update2: When I check the app today, it failed again. I did what the docs required with the "raw" method but no luck. A workaround is to use the "Per Page Encoding". This one I tested thoroughly. It does work.
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
这篇关于在GSP上发送JSON到JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!