![](/img/trans.png)
[英]error rendering a flash message with jquery ajax in ruby on rails app
[英]Ajax flash message in ruby on rails
我正在嘗試顯示一條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消息呢?
按設計的Flash消息存儲在會話中,直到下一頁加載。 在ajax的情況下,請勿使用閃光燈。 首先,替換消息的div可能不存在,因此您需要將其作為要添加的容器添加到頁面中。 其次,只是從常規變量,而不是閃存。
常規變量是:
@message = "Micropost created!"
而不是閃光[:成功]
js視圖將使用此變量而不是flash。
而不是page.replace_html :notice, flash[:notice]
試試這個page.replace_html :notice, "Some info to flash"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.