Rails 4 ajax flash消息导致非xhr请求的奇怪行为

时间:2014-02-09 22:23:09

标签: jquery ruby-on-rails ajax

我有一个Rails4应用程序,它在ajax请求上向jQuery提供flash消息。这非常有效。在非xhr请求中,但是我的代码行为不正常,在下一个ajax请求之前它不显示任何flash消息。

在控制器中的重定向中,不会显示任何闪存消息,但下次发出任何ajax请求时,将显示过时的闪存消息。

这是我的代码:

class ApplicationController < ActionController::Base

  respond_to :html
  after_action :flash_to_headers

private

  def flash_to_headers
    return unless request.xhr?
    response.headers['X-Message'] = flash_message
    response.headers["X-Message-Type"] = flash_type.to_s
    flash.discard # don't want the flash to appear when reloading the page
  end

  def flash_message
    [:error, :warning, :notice].each do |type|
      return flash[type] unless flash[type].blank?
    end
    # if we don't return the above code will give "error, warning, notice"
    return ''
  end

  def flash_type
    [:error, :warning, :notice].each do |type|
      return type unless flash[type].blank?
    end
  end

end


class SessionsController < ApplicationController

  def destroy
    # Sign-out user...
    redirect_to sign_in_path, warning: "Signed out successfully"
  end

end

CoffeeScript的:

  $(document).ajaxComplete (e, request) ->
    message = request.getResponseHeader('X-Message')
    type = request.getResponseHeader('X-Message-Type')
    if message
      MyApp.FlashManager.open(message, type)

1 个答案:

答案 0 :(得分:1)

当非ajax请求进入时,如何将Flash消息放在页面上?如果在HTML呈现期间没有在页面上呈现Flash消息,则flash将保留在队列中,直到您使用下一个ajax请求丢弃它。