1
我有一個Rails4應用程序,它正在向jQuery請求ajax請求上的Flash消息。這非常有效。然而,在非xhr請求中,我的代碼行爲異常,直到下一個ajax請求才顯示任何Flash消息。Rails 4 Ajax Flash消息導致非xhr請求的奇怪行爲
在控制器中重定向時,不顯示任何閃存消息,但下次發出任何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)
這真的讓我感到驚訝。我在構建這個功能的過程中,似乎只要我在Rails知道的地方調用flash [:notice](或警告或其他)。有趣。 – kequc