0

目前,这是我用于创建新消息的代码:

  if @message.save
    respond_to do |format|
      format.html { redirect_to messages_path }
      format.js
    end
  else
    flash[:notice] = "Message cannot be blank!"
    redirect_to :back
  end

如何在 Ajax 中打印相同的消息?还想控制它的格式和位置。

4

1 回答 1

2

应用程序控制器中

  after_filter :add_flash_to_header

  def add_flash_to_header
    # only run this in case it's an Ajax request.
    return unless request.xhr?

    # add different flashes to header
    response.headers['X-Flash-Error'] = flash[:error] unless flash[:error].blank?
    response.headers['X-Flash-Warning'] = flash[:warning] unless flash[:warning].blank?
    response.headers['X-Flash-Notice'] = flash[:notice] unless flash[:notice].blank?
    response.headers['X-Flash-Message'] = flash[:message] unless flash[:message].blank?

    # make sure flash does not appear on the next page
    flash.discard
  end

将通知代码移动到部分:

<div class="noticesWrapper">
  <% flash.each do |name, msg| %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert"><i class="icon-remove"></i></a>
      <%= msg %>
    </div>
  <% end %>
</div>

js.erb文件中:

$('.noticesWrapper').html("<%= j(render partial: 'layouts/flash_notices') %>");

在控制器操作中,您需要使用 flash.now 来闪烁消息:

flash.now[:error] = "your message"

于 2013-08-04T15:26:04.020 回答