如何将一个javascript变量传递到groovy块 [英] How to pass a javascript variable into a groovy block

查看:152
本文介绍了如何将一个javascript变量传递到groovy块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的javascript函数中管理一个groovy列表对象。
我有一个常用的JavaScript功能块。
我试过这个:

  var obj = $ {mediaObjectInstanceList as grails.converters.JSON} [index]; 

与此:

  var obj = $ {mediaObjectInstanceList.get(index)}; 

但两者都是错误的。在第二部分中,我将指定indexint javascript变量出于groovy块。

解决方案

正如Injecteer回答的那样,不能这样做。主要是因为:


  • groovy块在服务器端执行:它们无法识别JavaScript中只有浏览器才知道的变量。 li>
  • javascript执行客户端,即。浏览器不知道变量 mediaObjectInstanceList (仅由您的grails应用程序知道)。


两个(主要)解决方案:


  • 当页面生成时,您不知道您的索引(no params in你需要)=>你必须生成整个数组服务器端(groovy),以便在客户端(javascript)可用。


    $ b $ var mediaObjectInstanceListInJS = new Array($ { mediaObjectInstanceList.collect {it as JSON} .join(',')});
    var someVal = mediaObjectInstanceListInJS [index];


  • 您已经拥有索引服务器端(在您的请求中带有参数)=> groovy仅阻止您选择的对象:



    var someVal = $ {mediaObjectInstanceListInJS [params.index] as JSON};



I need to manage a groovy list object in my javascript function. I have a groovy block into a javascript function. 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.

解决方案

As answered by injecteer, you can't do that. Mostly because :

  • groovy blocks are executed server side : they can't be aware of variables in javascript only know by the browsers.
  • javascript is executed client side, ie. browsers don't know the variable mediaObjectInstanceList (only known by your grails application).

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).

    var mediaObjectInstanceListInJS = new Array( ${mediaObjectInstanceList.collect { it as JSON}.join(',')} ); 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 :

    var someVal = ${mediaObjectInstanceListInJS[params.index] as JSON} ;

这篇关于如何将一个javascript变量传递到groovy块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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