ruby on Rails 中的 Ajax Flash 消息
我正在尝试显示一条 Flash 消息并使用 Ajax 渲染它,但该消息似乎直到我刷新页面后才显示。
这是我的 create.rjs 文件:
page.insert_html :top, :feed_items, :partial => 'shared/feed_item', :object => @micropost
page.replace_html :user_info, pluralize(current_user.microposts.count, "micropost")
page[:micropost_form].reset
page.replace_html :notice, flash[:notice]
flash.discard
这是我的应用程序布局视图:
<div id= "notice"><% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %></div>
这是我的微帖子控制器的相关部分:
class MicropostsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
before_filter :authorized_user, :only => :destroy
def create
@micropost = current_user.microposts.build(params[:micropost])
respond_to do |format|
if @micropost.save
flash[:success] = "Micropost created!"
format.html { redirect_to root_path }
format.js
else
@feed_items = []
render 'pages/home'
end
end
end
那么为什么 Flash 消息没有立即显示?
I'm trying to show a flash message and render it with Ajax, but the message does not seem to be appearing until after I refresh the page.
Here's my create.rjs file:
page.insert_html :top, :feed_items, :partial => 'shared/feed_item', :object => @micropost
page.replace_html :user_info, pluralize(current_user.microposts.count, "micropost")
page[:micropost_form].reset
page.replace_html :notice, flash[:notice]
flash.discard
Here's the relevant part of my application layout view:
<div id= "notice"><% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %></div>
And here's the relevant part of my micropost controller:
class MicropostsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
before_filter :authorized_user, :only => :destroy
def create
@micropost = current_user.microposts.build(params[:micropost])
respond_to do |format|
if @micropost.save
flash[:success] = "Micropost created!"
format.html { redirect_to root_path }
format.js
else
@feed_items = []
render 'pages/home'
end
end
end
So why isn't the flash message showing up right away?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Flash 消息按照设计存储在会话中,直到加载下一个页面。在ajax的情况下,不要使用flash。一方面,要替换消息的 div 可能不存在,因此您需要将其作为要添加的容器添加到页面中。其次,只需从常规变量(而不是 Flash)执行此操作。
常规变量将是:
而不是 flash[:success]
js 视图将使用此变量而不是 flash。
Flash messages by design are stored in the session until the next page load. In the case of ajax, don't use flash. For one thing, the div to replace the message into may not exist, so you need to add that to your page as a container to add to. Second, just do it from a regular variable, not flash.
A regular variable would be:
instead of the flash[:success]
The js view would use this variable instead of flash.
而不是
page.replace_html :notice,flash[:notice]
试试这个
page.replace_html :notice, "Some info to flash"
Instead of
page.replace_html :notice, flash[:notice]
Try this
page.replace_html :notice, "Some info to flash"