[英]How to pass a javascript variable into a groovy block
I need to manage a groovy list object in my javascript function. 我需要在我的javascript函数中管理一个常规列表对象。 I have a groovy block into a javascript function. 我在javascript函数中有一个常规代码块。 I tried with this: 我尝试了这个:
var obj = ${mediaObjectInstanceList as grails.converters.JSON}[index];
and this: 和这个:
var obj = ${mediaObjectInstanceList.get(index)};
but both are wrong. 但两者都是错误的。 In the second I would specify the "index" int javascript variable out of the groovy block. 在第二个中,我将在groovy块中指定“ index” int javascript变量。
You can't do that in a way you defined it. 您无法以定义方式进行操作。
Though, there are lots of possibilities to accomplish that. 虽然,有很多可能性可以做到这一点。
One of them is to define a JS-variable and fill it with groovy model values: 其中之一是定义一个JS变量,并用常规模型值填充它:
var myArray = new Array(
<g:each in="${mediaObjectInstanceList}" var="obj" status="ix">
${status ? ',' : ''} '${obj}'
</g:each>
);
then you can traverse this array in JS using plain subscript notation: 那么您可以使用简单的下标符号在JS中遍历此数组:
var someVal = myArray[ index ];
As answered by injecteer, you can't do that. 正如注射者的回答,您不能那样做。 Mostly because : 主要是因为:
mediaObjectInstanceList
(only known by your grails application). 浏览器不知道变量mediaObjectInstanceList
(只有grails应用程序知道)。 Two (main) solutions : 两种(主要)解决方案:
you don't know your index when the page is generated (no params in your request) => You have to generate the whole array server side (groovy) to be available at client side (javascript). 您不知道生成页面时的索引(请求中没有参数)=>您必须生成整个数组服务器端(常规)才能在客户端使用(javascript)。
var mediaObjectInstanceListInJS = new Array( ${mediaObjectInstanceList.collect { it as JSON}.join(',')} ); var mediaObjectInstanceListInJS = new Array($ {mediaObjectInstanceList.collect {它为JSON} .join(',')}); var someVal = mediaObjectInstanceListInJS[index]; var someVal = mediaObjectInstanceListInJS [index];
you already have the index server side (with params in your request) => you can get in groovy block only your selected object : 您已经具有索引服务器端(在请求中带有参数)=>您只能在groovy块中获得所选对象:
var someVal = ${mediaObjectInstanceListInJS[params.index] as JSON} ; var someVal = $ {mediaObjectInstanceListInJS [params.index] as JSON};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.