我想从 Controller 发送一些 JS 脚本到 GSP View 。 我做了以下尝试。
Controller (Purchase.groovy):
def myaction={
flash.script= 'jQuery("div#header").show(1000);'
redirect(action:'edit')
}
在purchase/myaction.gsp文件中, 我试试下面的代码
<g:if test="${flash.script !=null}">
<g:javascript>
$(function() {
${flash.script}
})
</g:javascript>
</g:if>
<g:else>
<g:javascript>
$(function() {
alert('Welcome')
})
</g:javascript>
</g:else>
我也尝试:jQuery.getScript('${flash.script}')
而不是 '${flash.script}'
但是,GSP 页面始终呈现第二个脚本(else 语句)
最佳答案
首先,一定要在dom加载完成后调用该函数;你可以像这样使用 jquery
$( document ).ready(function() {
call_function();
});
并且您可以将 js 代码形式的 Controller 作为 map 发送,而不是通过 flash 并重定向到另一个操作。见下文:
def myaction={
redirect(action:'edit', customJs: 'jQuery("div#header").show(1000);')
}
def edit={
render view: 'someView', model:[customJs: customJs]
}
在 View 中:
<g:javascript>
$(function() {
<%= customJs %>
})
关于javascript - 如何将 Javascript 代码从 Controller 发送到 GSP View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16519359/