正确地将Groovy列表传递给GSP中的Javascript代码 [英] Correctly pass a Groovy list to Javascript code in GSP

查看:87
本文介绍了正确地将Groovy列表传递给GSP中的Javascript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Grails制作一个Web应用程序。我列出了必须包含在JavaScript中的数据以在< select> 下拉列表上执行一些动态加载。基本上,我从服务器获取两级列表,然后第一级显示在下拉框中。当用户选择一个选项时,与该选项关联的列表会显示在另一个下拉框中。



JavaScript函数的gsp页面上的(简化)代码是以下

 函数selecTipe(){
var types = $ {typeList}
alert('List of类型'+类型)

问题是,如果typeList在Groovy中定义为



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

当页面被渲染时,JavaScript代码就像

 函数selecTipe(){
var types = [[TYPE1,[VAR1,VAR2,VAR3]],
[TYPE2,[VAR1,VAR2,VAR3]]
[TYPE3,[VAR1,VAR2,VAR3]]]
alert( '类型列表'+类型)

这是错误的,因为JavaScript不会将它视为字符串,而是作为缺少引号的引用。



有什么办法可以强制Groovy使用引号或其他简单的方法来打印数组列表?



PD:我可以创建一个特定的函数来实现它,但我认为它应该是一个简单的方法来实现它...



编辑:我已经添加了完整的数据结构,因为它比简单的列表更复杂一些

解决方案

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


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

解决方案

Try this in your grails controller's action :

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

这篇关于正确地将Groovy列表传递给GSP中的Javascript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆