简体   繁体   English

如何将Javascript代码从Controller发送到GSP视图?

[英]How to send Javascript code from Controller to GSP view?

I want to send some JS Script from controller to GSP view . 我想从控制器向GSP视图发送一些JS脚本。 I do the following attempt. 我做以下尝试。

Controller(Purchase.groovy) : 控制器(Purchase.groovy):

 def myaction={
     flash.script= 'jQuery("div#header").show(1000);'
     redirect(action:'edit')
}

In purchase/myaction.gsp file, I try the following code 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>

I try also : jQuery.getScript('${flash.script}') instead of '${flash.script}' However, GSP page renders always the second script(else statement) 我也尝试: jQuery.getScript('${flash.script}')而不是'${flash.script}'但是,GSP页面始终呈现第二个脚本(其他语句)

First of all, be sure to call the function after the dom loaded; 首先,一定要在dom加载后调用该函数; u can use jquery like 你可以像这样使用jQuery

  $( document ).ready(function() {
     call_function();
  });

And you can send js code form controller as map, not through flash and redirecting to another action. 您可以将js代码形式的控制器发送为地图,而无需通过Flash并重定向到其他操作。 See below: 见下文:

 def myaction={
    redirect(action:'edit', customJs: 'jQuery("div#header").show(1000);')
 }

 def edit={
   render view: 'someView', model:[customJs: customJs]
}

And in view: 并且鉴于:

 <g:javascript>
$(function() {

        <%= customJs %>
})

flash.script is fine, I tested here and it works. flash.script很好,我在这里测试了并且可以正常工作。 What happens is that flash object is for transition, and will be available only in the next request. 发生的情况是flash对象用于过渡,并且仅在下一个请求中可用。 If your page is redirected to edit and you refresh edit , then flash will not be there anymore. 如果您的页面被重定向到edit并刷新了edit ,则Flash将不再存在。 Example: 例:

  • Go to myaction; 去行动吧;
  • Flow will redirect to edit; 流将重定向到编辑;
  • If you refresh the page, welcome will be printed. 如果刷新页面,将打印欢迎信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM