简体   繁体   English

在 GSP 上将 JSON 发送到 javascript

[英]Sending JSON to javascript on GSP

I'm using Grails 2.3.7 and I have a controller action as follows:我正在使用 Grails 2.3.7 并且我有一个控制器操作,如下所示:

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:在 testData.gsp 中,我想在 javascript 中获取 JSON 对象:

<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({&quot;name&quot;:&quot;Sales&quot;,&quot;type&quot;:&quot;bar&quot;,&quot;data&quot;:[5,20,45,10,10,20]});

It looks like JSON is messed up.看起来 JSON 搞砸了。 I think it used to work this way.我认为它曾经以这种方式工作。 Maybe it's new Grails?也许这是新的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.更新 2:当我今天检查应用程序时,它再次失败。 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.问题是 JSON 被编码为 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你不需要$(document).ready因为 JS 代码

var data = ${raw(data)};

is generated on the server-side在服务器端生成

Working solution :工作解决方案

def action() {
  [data: data as JSON]
}

GSP page: GSP页面:

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

The encodeAsJSON() method works well for outputting JSON data into JavaScript: encodeAsJSON()方法非常适合将 JSON 数据输出到 JavaScript:

Controller控制器

def testData() {
   def data = [name: "Sales", values: [5, 20, 45]]
   [data: data]
   }

View (GSP)查看 (GSP)

<script>
var data1 = ${raw(data)};  //{name=Sales, values=[5, 20, 45]}
var data2 = ${raw(data as grails.converters.JSON)};  //{&quot;name&quot;:&quot;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 &quot;在 Groovy 对象上使用raw()不会产生与 JavaScript 兼容的输出(请参阅data1 ),并且在 JSON 转换器之后使用它会导致不需要的&quot; encoding (see data2 ).编码(见data2 )。 Using encodeAsJSON() produces the correct output (see data3 ).使用encodeAsJSON()会产生正确的输出(请参阅data3 )。

Documentation:文档:
http://grails.org/doc/latest/guide/security.html#codecs http://grails.org/doc/latest/guide/security.html#codecs

Update:更新:
I've switched to using a taglib with:我已经改用taglib了:

out << "<script>var data = " + raw((data as JSON) as String) + ";</script>"

The following worked for me using Grails 2.4.3:以下使用 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: Dónal 接受的答案对我不起作用:

Controller (same as my working example above)控制器(与我上面的工作示例相同)

GSP (did NOT work): GSP(不起作用):

<script>
// did NOT work!!
var data = ${raw(data)};
</script>

Produced same bad result:产生了同样的坏结果:

<script>
// did NOT work!!
var data = {&quot;type&quot;:&quot;bar&quot;,&quot;data&quot;:[5,20,45]};
</script>

This worked for me in grails 3.1.9.这在 grails 3.1.9 中对我有用。

Controller:控制器:

def result = [:]
result['type'] = "bar"
result['data'] = [5,20,45]
result['key'] = token

[data:result as JSON]

GSP:普惠制:

<script>

var data = '${raw(data as String)}';
var json = JSON.parse(data);
alert(json.type);

var authorization = json.key;

</script>

Not all grails versions support raw() method or g:applyCodec taglib.并非所有 grails 版本都支持 raw() 方法或 g:applyCodec 标签库。

The solution is to use <%= %> block to avoid escaping解决方法是使用 <%= %> 块来避免转义

 <%= users.collect({id:it.id,value:it.name}) as grails.converters.JSON%>

OR或者

<%= someJsString.encodeAsJavascript() %>

But best practice is to avoid using serverside generated JSON into GSP and refactor into getting the same JSON received via ajax request但最佳实践是避免将服务器端生成的 JSON 用于 GSP 并重构为通过 ajax 请求获得相同的 JSON

In testData.gsp add在 testData.gsp 添加

<%@page expressionCodec="none" %>

and in script并在脚本中

<script>
   $(document).ready(function(){
    var data = ${data};
})
</script>

This might also help, passing data as simple model and parsing it as JSON in gsp.这也可能有所帮助,将数据作为简单模型传递并将其解析为 gsp 中的 JSON。

def testData() {
    def result = [:]
    ...
    [data: result]
}

On View在查看

<%! import grails.converters.JSON %>
...
<script>
function parseModelToJS(jsonString)
{
 jsonString=jsonString.replace(/\"/g,'"');
 var jsonObject=$.parseJSON(jsonString);
 return jsonObject
}

$(document).ready(function(){
 var data=parseModelToJS('${data as JSON}');
 console.log(data);
});
</script>

http://www.oodlestechnologies.com/blogs/Parse-model-to-json-on-gsp-in-grails http://www.oodlestechnologies.com/blogs/Parse-model-to-json-on-gsp-in-grails

You can do this,你可以这样做,

import groovy.json.*
Map testMap = ['name': 'Test']
String jsonData = new JsonBuilder(testMap).toPrettyString()
render(view: view, model: ["data": jsonData], params: [:])

In your gsp:在您的 gsp 中:

 <script>
    var data = ${raw(data)};
</script>

Simple..简单的..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM