Ruby on Rails中的Ajax闪光灯消息闪光灯、消息、on、Ruby

2023-09-10 17:58:48 作者:爱吃喵的鱼

我试图表现出显信息,并使用Ajax呈现它,但似乎该消息并没有现身后我才刷新页面。

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.

下面是我的create.rjs文件:

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>

这是我的micropost控制器的相关部分:

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?

推荐答案

在设计的Flash消息存储在会话中,直到下一个页面加载。在AJAX的情况下,不要使用闪光灯。一方面,股利更换消息到可能不存在,所以你需要添加到您的网页作为容器添加到。其次,只是从一个普通的变量,不闪。

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.

一个常规的变量是:

@message = "Micropost created!"

而不闪

[:成功]

instead of the flash[:success]

JS的看法会用闪存代替这个变量。

The js view would use this variable instead of flash.