将 Groovy 列表正确传递给 GSP 中的 Javascript 代码 [英] Correctly pass a Groovy list to Javascript code in GSP
问题描述
我正在使用 Grails 制作 Web 应用程序.我有一个包含必须包含在 JavaScript 中的数据的列表,以便在 下拉列表上执行一些动态加载.基本上,我从服务器获取两级列表,然后第一级显示在下拉框上.当用户选择一个选项时,与该选项关联的列表会显示在另一个下拉框中.
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.
gsp 页面上 JavaScript 函数的(简化)代码如下
The (simplified) code on the gsp page for the JavaScript function is the following
function selecTipe() {
var types = ${typeList}
alert('List of types ' + types )
问题在于,如果 typeList 被定义为(在 Groovy 中)
The problem is that, if typeList is defined (in Groovy) as
typeList = [['TYPE1', ['VAR1','VAR2','VAR3']],
['TYPE2', ['VAR1','VAR2','VAR3']]
['TYPE3', ['VAR1','VAR2','VAR3']] ]
当页面被渲染时,JavaScript 代码看起来像
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 )
这是错误的,因为 JavaScript 没有将其视为字符串,而是由于缺少引号而将其视为引用.
which is erroneous, as JavaScript treats then not as strings, but as references due the lack of quotes.
有什么方法可以强制 Groovy 打印带引号的数组列表或任何其他简单的方法来实现这一点?
Is there any way to force Groovy to print a list of arrays with quotes or any other easy way to achieve this?
PD:我可以做一个特定的功能来实现它,但我认为这应该是一个简单的方法......
PD: I can make an specific function to achieve it, but I think it should be an easy way to do that...
我添加了完整的数据结构,因为它比简单的列表稍微复杂一些
I've added the complete data structure, as is a little more complex than a simple list
推荐答案
在你的 grails 控制器的操作中试试这个:
Try this in your grails controller's action :
def types = ['TYPE1', 'TYPE2', 'TYPE3'] as grails.converters.JSON
[typeList : types]
这篇关于将 Groovy 列表正确传递给 GSP 中的 Javascript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!