grails - 如何将 JSON 数组传递给我的 GSP 页面上的 JavaScript 变量?

标签 grails gsp

我有以下 Controller 操作:

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

在我的 GSP 上,我可以输出以下数据参数:
${data}

由于数据代表有效的 JSON,我想在我的 GSP 上的 JavaScript block 中使用它。
<script type="text/javascript">
var data = [
            { Date: "2015-09-14", DayOfMonth: 14, Type: "Views", Amount: 0, y1: 10, }
           ];
</script>

替换硬编码的 JSON 变量。我知道我可以用这样的字符串进行替换:
<script type="text/javascript">
var data = "${data}";
</script>

或者
<script type="text/javascript">
var data = "${raw(data)}";
</script>

前者可以很好地工作原始类型,如字符串,但如果我将 JSON 数组传递给 JavaScript 变量,它会失败。当我在控制台中打印 JavaScript 数据变量的内容时,我得到:
[{&quot;Date&quot;:&quot;2015-09-13T22:00:00Z&quot;,&quot;DayOfMonth&quot;:14,&quot;Type&quot;:&quot;Views&quot;,&quot;Amount&quot;:1}]

如何将 JSON 数组传递给我的 GSP 页面上的 JavaScript 变量?

最佳答案

这似乎是一个尚未解决的编码问题。

解决方案一 - 在本地禁用编码器

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

解决方案二 - 影响整个页面
<%@page defaultCodec="none" %>

解决方案3 - 使用自定义标签
class MyTagLib {
    static defaultEncodeAs = [taglib:'none']

    def writeWithoutEncoding = {attrs ->
        out << attrs.input
    }
}

并在 GSP 页面中:
var data = <g:writeWithoutEncoding input="${data}"/>;

引用文献:https://jira.grails.org/browse/GRAILS-11829http://aruizca.com/how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag/

关于grails - 如何将 JSON 数组传递给我的 GSP 页面上的 JavaScript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32888284/

相关文章:

grails - 在 Groovy 闭包内更新 "it"

grails - Grails Action 被两次调用

grails - 使用<g:select> grails

ajax - chalice /AJAX : Updating an arbitrary region in the page using g:submitToRemote

grails - grails 是否支持在 gsp 页面中使用 JSTL 核心 taglib 中的 "forEach"?

grails - 在GSP中导入类的正确方法是什么?

hibernate - 使用 Grails GORM 从旧数据库中的 char 字段中去除尾随空格

grails - 递归方法在grails/groovy单元测试用例中无法正常工作

mysql - Grails 数据库映射

eclipse - 如何使用Mongo为Birt编写表达式?