Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

grails - Correctly pass a Groovy list to Javascript code in GSP

I'm making a web application with Grails. I've got a list with data that must be included on JavaScript to perform some dynamic load on <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

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

The problem is that, if typeList is defined (in Groovy) as

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

when the page is renderized, the JavaScript code appears like

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.

Is there any way to force Groovy to print a list of arrays with quotes or any other easy way to achieve this?

PD: I can make an specific function to achieve it, but I think it should be an easy way to do that...

EDIT: I've added the complete data structure, as is a little more complex than a simple list

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this in your grails controller's action :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...