[英]How to pass a value directly from a controller to a javascript file in Grails
Would like to pass directly from the controller to a JavaScript file. 想要直接从控制器传递到JavaScript文件。
TestControler.groovy TestControler.groovy
def list() {
render (view: "list", model:[theId: theId])
}
Test.js Test.js
function test() {
// do smth with theId
}
Found solution have the rendered gsp in the middle, ie this one , but I would like to know if there is a way to avoid that including using hidden fields or having in the gsp file a javascript code snippet such as: 找到的解决方案在中间显示了gsp,即这个 ,但我想知道是否有一种方法可以避免这种情况,包括使用隐藏字段或在gsp文件中包含一个javascript代码段,例如:
<g:javascript>
function test(${theId}) {
// do smth with theId
}
</g:javascript>
Unfortunately there does not seem to be anything that covers what you're looking for. 不幸的是,似乎没有任何东西可以满足您的需求。 The best approach that I have seen, and have used myself, is to use hidden fields in the gsp/html, and retrieve those values from javascript on the client side. 我所见并用过的最好的方法是使用gsp / html中的隐藏字段,并从客户端的javascript中检索这些值。
I have had similar issue this is how I solved it. 我有类似的问题,这就是我解决的方法。
say you have this controller: 说你有这个控制器:
def list() {
render (view: "list", model:[theId: theId])
}
Then on your view( list.gsp) 然后在您的视图(list.gsp)
<g:javascript>
var theId = ${theId}
</g:javascript>
Then your function on the external file can do anything with variable theId
because it global variable. 然后,外部文件上的函数就可以使用变量theId
进行任何操作,因为它是全局变量。
function test() {
// do smth with theId
}
Personally I was having a complex json object so instead of coding the json into html and prasing it back to json when needed on the client side, I just put it as js json variable from my gsp and then I can do whatever I want from the client side 我个人有一个复杂的json对象,因此我不需要将json编码为html并在客户端需要时将其赞回json,而是将其作为gsp中的js json变量,然后我可以从客户端
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.