我如何在JavaScript中访问Grails变量? [英] How can I access a Grails variable in JavaScript?

查看:110
本文介绍了我如何在JavaScript中访问Grails变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Grails应用程序中有一个变量 BootStrap.groovy

  class BootStrap {
def init = {servletContext - >
def testGrails =11

我想要显示一个JavaScript alert()如果此测试值为11。



我的JavaScript:

 < SCRIPT LANGUAGE =JavaScript> 
if(testGrails == 11)//在支架中写什么...?
{
alert(yes);





$ b

如何访问JavaScript中的Grails类来完成上述操作? p>

谢谢。

解决方案

首先 - 必须使这个变量从其他地方访问。目前它的界限是 init 范围。例如,您可以将其放入全局配置中(请参阅 Config.groovy )。或者设置为服务。或者在某处制作 public static 变量。



服务示例:

  class VariableHOlderService {

def testGrails

}
pre>

  class BootStrap {

VariableHolderService variableHolderService

def init = {servletContext - >
VariableHolderService.testGrails =11
}

其次 - 您需要把它要求。有两种方法 - 使用过滤器或控制器/动作。当你想从不同的GSP使用相同的变量时,第一个选项很有用。



从控制器开始:

  VariableHolderService variableHolderService 

def myAction = {
render model:[testGrails:variableHolderService.testGrails]
}

并在GSP中使用它作为

 < G:的javascript> 
if($ {testGrails} == 11)
{
alert(yes);
}
< / g:javascript>


I have a variable in my Grails app’s BootStrap.groovy:

      class BootStrap {
      def init = { servletContext ->
      def testGrails = "11"

I want to show a JavaScript alert() if this test value is 11.

My JavaScript:

           <SCRIPT LANGUAGE="JavaScript">
           if(testGrails==11)   // WHAT TO WRITE WITH IN THE BRACKETS ...?
           {
               alert("yes");
           }        

How can I access a Grails class in Javascript to do the above?

Thanks.

解决方案

First of all - you have to make this variable accessible from other places. Currently it's bounded to init scope. You can put it into global config for example (see Config.groovy). Or set to an service. Or make an public static variable somewhere.

Example for a service:

class VariableHOlderService {

    def testGrails

}

and

class BootStrap {

      VariableHolderService variableHolderService

      def init = { servletContext ->
          VariableHolderService.testGrails = "11"
}

Second - you need to put it into request. There is two ways - use filter or controller/action. First option is useful when you want to use same variable from different GSP.

From controller it would be:

VariableHolderService variableHolderService

def myAction = {
    render model: [testGrails:variableHolderService.testGrails]
}

and use it at GSP as

<g:javascript>
       if(${testGrails}==11)   
       {
           alert("yes");
       }    
</g:javascript>

这篇关于我如何在JavaScript中访问Grails变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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