Jus*_*zer 2 javascript ruby ajax ruby-on-rails rjs
我正在尝试显示一条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
Run Code Online (Sandbox Code Playgroud)
这是我的应用程序布局视图的相关部分:
<div id= "notice"><% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %></div>
Run Code Online (Sandbox Code Playgroud)
这是我的微控制器的相关部分:
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
Run Code Online (Sandbox Code Playgroud)
那么为什么不立即显示flash消息呢?
按设计的Flash消息存储在会话中,直到下一页加载.在ajax的情况下,请勿使用闪光灯.首先,替换消息的div可能不存在,因此您需要将其作为要添加的容器添加到页面中.其次,只是从常规变量,而不是闪存.
常规变量是:
@message = "Micropost created!"
Run Code Online (Sandbox Code Playgroud)
而不是闪光[:成功]
js视图将使用此变量而不是flash.
| 归档时间: |
|
| 查看次数: |
4133 次 |
| 最近记录: |