Jquery Rails 4 ajax flash消息会导致非xhr请求的奇怪行为
我有一个Rails4应用程序,它在ajax请求上向jQuery提供flash消息。这真是妙不可言。在非xhr请求上,尽管我的代码表现不好,但在下一个ajax请求之前,它不会显示任何flash消息 在控制器中的重定向上,不会显示flash消息,但下一次发出任何ajax请求时,会显示过时的flash消息 这是我的密码:Jquery Rails 4 ajax flash消息会导致非xhr请求的奇怪行为,jquery,ruby-on-rails,ajax,Jquery,Ruby On Rails,Ajax,我有一个Rails4应用程序,它在ajax请求上向jQuery提供flash消息。这真是妙不可言。在非xhr请求上,尽管我的代码表现不好,但在下一个ajax请求之前,它不会显示任何flash消息 在控制器中的重定向上,不会显示flash消息,但下一次发出任何ajax请求时,会显示过时的flash消息 这是我的密码: class ApplicationController < ActionController::Base respond_to :html after_action
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
当收到非ajax请求时,如何将flash消息放在页面上?如果在HTML呈现过程中没有在页面上呈现flash消息,flash将留在队列中,直到您在下一个ajax请求中放弃它。这让我非常惊讶。我在构建这个功能的中途,似乎只要我在Rails知道的地方调用flash[:notice](或warning)或其他任何东西。有趣。
$(document).ajaxComplete (e, request) ->
message = request.getResponseHeader('X-Message')
type = request.getResponseHeader('X-Message-Type')
if message
MyApp.FlashManager.open(message, type)