如何将值直接从控制器传递到 Grails 中的 javascript 文件
How to pass a value directly from a controller to a javascript file in Grails
想直接从控制器传递到 JavaScript 文件。
TestControler.groovy
def list() {
render (view: "list", model:[theId: theId])
}
Test.js
function test() {
// do smth with theId
}
找到的解决方案在中间有渲染的 gsp,即 this one,但我想知道是否有办法避免这种情况,包括使用隐藏字段或在 gsp 文件中有一个 javascript 代码片段如:
<g:javascript>
function test(${theId}) {
// do smth with theId
}
</g:javascript>
很遗憾,似乎没有任何内容可以满足您的需求。我见过并自己使用过的最好方法是在 gsp/html 中使用隐藏字段,并从客户端的 javascript 中检索这些值。
我遇到过类似的问题,我就是这样解决的。
假设你有这个控制器:
def list() {
render (view: "list", model:[theId: theId])
}
那么在你看来(list.gsp)
<g:javascript>
var theId = ${theId}
</g:javascript>
那么你在外部文件上的函数可以对变量 theId
做任何事情,因为它是全局变量。
function test() {
// do smth with theId
}
就我个人而言,我有一个复杂的 json 对象,所以不是将 json 编码为 html 并在客户端需要时将其返回 json,我只是把它作为我的 gsp 中的 js json 变量然后我可以从客户端做任何我想做的事
想直接从控制器传递到 JavaScript 文件。
TestControler.groovy
def list() {
render (view: "list", model:[theId: theId])
}
Test.js
function test() {
// do smth with theId
}
找到的解决方案在中间有渲染的 gsp,即 this one,但我想知道是否有办法避免这种情况,包括使用隐藏字段或在 gsp 文件中有一个 javascript 代码片段如:
<g:javascript>
function test(${theId}) {
// do smth with theId
}
</g:javascript>
很遗憾,似乎没有任何内容可以满足您的需求。我见过并自己使用过的最好方法是在 gsp/html 中使用隐藏字段,并从客户端的 javascript 中检索这些值。
我遇到过类似的问题,我就是这样解决的。
假设你有这个控制器:
def list() {
render (view: "list", model:[theId: theId])
}
那么在你看来(list.gsp)
<g:javascript>
var theId = ${theId}
</g:javascript>
那么你在外部文件上的函数可以对变量 theId
做任何事情,因为它是全局变量。
function test() {
// do smth with theId
}
就我个人而言,我有一个复杂的 json 对象,所以不是将 json 编码为 html 并在客户端需要时将其返回 json,我只是把它作为我的 gsp 中的 js json 变量然后我可以从客户端做任何我想做的事