简体   繁体   English

正确地将Groovy列表传递给GSP中的Javascript代码

[英]Correctly pass a Groovy list to Javascript code in GSP

I'm making a web application with Grails. 我正在用Grails制作一个Web应用程序。 I've got a list with data that must be included on JavaScript to perform some dynamic load on <select> drop-list. 我有一个列表,其中包含必须包含在JavaScript中的数据,以便在<select> drop-list上执行一些动态加载。 Basically, I'm getting a two level list from the server, then the first level is presented on a drop box. 基本上,我从服务器获得一个两级列表,然后第一级显示在一个下拉框中。 When the user selects an option, the list associated to this option is presented on another drop box. 当用户选择一个选项时,与该选项关联的列表将显示在另一个下拉框中。

The (simplified) code on the gsp page for the JavaScript function is the following JavaScript函数的gsp页面上的(简化)代码如下

function selecTipe() {
        var types = ${typeList}
        alert('List of types ' + types )

The problem is that, if typeList is defined (in Groovy) as 问题是,如果将typeList定义为(在Groovy中)为

typeList = [['TYPE1', ['VAR1','VAR2','VAR3']], 
            ['TYPE2', ['VAR1','VAR2','VAR3']]
            ['TYPE3', ['VAR1','VAR2','VAR3']] ]

when the page is renderized, the JavaScript code appears like 当页面重新定义时,JavaScript代码显示为

function selecTipe() {
        var types = [[ TYPE1, [ VAR1, VAR2, VAR3 ]], 
                     [ TYPE2, [ VAR1, VAR2, VAR3 ]]
                     [ TYPE3, [ VAR1, VAR2, VAR3 ]] ]
        alert('List of types ' + types )

which is erroneous, as JavaScript treats then not as strings, but as references due the lack of quotes. 这是错误的,因为JavaScript不是作为字符串处理,而是因为缺少引号而作为引用。

Is there any way to force Groovy to print a list of arrays with quotes or any other easy way to achieve this? 有没有办法强制Groovy打印带引号的数组列表或任何其他简单的方法来实现这一目标?

PD: I can make an specific function to achieve it, but I think it should be an easy way to do that... PD:我可以做一个特定的功能来实现它,但我认为这应该是一个简单的方法...

EDIT: I've added the complete data structure, as is a little more complex than a simple list 编辑:我添加了完整的数据结构,比简单的列表更复杂

Try this in your grails controller's action : 在grails控制器的操作中尝试这个:

def types = ['TYPE1', 'TYPE2', 'TYPE3'] as grails.converters.JSON
[typeList : types]

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

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