2

I want to send some JS Script from controller to GSP view . I do the following attempt.

Controller(Purchase.groovy) :

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

In purchase/myaction.gsp file, I try the following code

<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)

2 Answers 2

5

First of all, be sure to call the function after the dom loaded; u can use jquery like

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

And you can send js code form controller as map, not through flash and redirecting to another action. 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 %>
})

Sign up to request clarification or add additional context in comments.

1 Comment

Passing a customJs as a parameter in redirect is a security hole/XSS
1

flash.script is fine, I tested here and it works. What happens is that flash object is for transition, and will be available only in the next request. If your page is redirected to edit and you refresh edit, then flash will not be there anymore. Example:

  • Go to myaction;
  • Flow will redirect to edit;
  • If you refresh the page, welcome will be printed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.