How to show flash.message in Grails after AJAX call

耗尽温柔 提交于 2019-12-14 02:05:40

问题


I want to show some flash message after completion of AJAX call. I am doing like this ..

Controller Action --

def subscribe()
{
    def subscribe = new Subscriber()
    subscribe.email = params.subscribe
    if (subscribe.save())
    {
        flash.message = "Thanks for your subscribtion"
    }

}

View Part --

Subscribe :
    <g:formRemote onSuccess="document.getElementById('subscribeField').value='';" url="[controller: 'TekEvent', action: 'subscribe']" update="confirm" name="updateForm">
       <g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
       <g:submitButton name="Submit" />
    </g:formRemote >
    <div id="confirm">
       <g:if test="${flash.message}">
           <div class="message" style="display: block">${flash.message}</div>
       </g:if>
    </div>

My AJAX working fine but it is not showing me flash.message. After refresh page it displaying message. How to solve it ?


回答1:


When you use ajax your page content isn't re-parsed, so your code:

<g:if test="${flash.message}">
  <div class="message" style="display: block">${flash.message}</div>
</g:if>

will not run again.

So I agree with @James comment, flash is not the better option to you.

If you need to update your view, go with JSON. Grails already have a converter that can be used to this:

if (subscribe.save()) {
  render ([message: "Thanks for your subscribtion"] as JSON)
}

And your view:

<g:formRemote onSuccess="update(data)" url="[controller: 'TekEvent', action: 'subscribe']"  name="updateForm">
  <g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
  <g:submitButton name="Submit" />
</g:formRemote >

<script type='text/javascript'>
  function update(data) {
    $('#subscribeField').val('');
    $('#confirm').html(data.message);
  }
</script>



回答2:


You have couple options, First you can try to return the message from your controller in a form of json or a map and render it on the screen your self using javascript libraries, which is a bit different if you want to use Grails ajax tags.

The other option is using a plugin like one-time-data , which

Summary A safe replacement for "flash" scope where you stash data in the session which can only be read once, but at any point in the future of the session provided you have the "id" required.

Description This plugin provides a multi-window safe alternative to flash scope that makes it possible to defer accessing the data until any future request (so long as the session is preserved). more

Hope it helps



来源:https://stackoverflow.com/questions/17920323/how-to-show-flash-message-in-grails-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!