我在主页上使用自定义注册模式(使用设计),并且使用闪存来存储错误并将其显示在自定义注册模式上。我想知道的是我是否可以使用javascript检查flash中是否有任何消息,如果是的话,我可以在重定向到主页时自动打开模式。因此,本质上我需要可以执行以下操作的 javascript:
Are there messages stored using flash?
If so, open modal when homepage loads.
我已经可以在使用js加载主页时打开模式,但我不知道如何检查flash中是否有消息。是否可以使用js访问flash并检查存储是否有错误?谢谢!
编辑:
所以我对 AJAX 完全陌生,但我遵循了这个:http://ashleyangell.com/2010/10/handling-rails-flash-message-with-ajax-requests/
我将以下内容添加到我的应用程序 Controller 中:
after_filter :flash_headers
def flash_headers
return unless request.xhr?
response.headers['x-flash'] = flash[:error] unless flash[:error].blank?
response.headers['x-flash'] = flash[:notice] unless flash[:notice].blank?
response.headers['x-flash'] = flash[:warning] unless flash[:warning].blank?
# Stops the flash appearing when you next refresh the page
flash.discard
end
我有以下 JavaScript:
$(document).load(function(){
$.ajax({
var flash = response.getHeader('x-flash');
if (flash) alert(flash);
});
});
现在,我在下面的行中遇到了“意外标识符”问题,并且当存在闪光通知时,警报不会显示。
var flash = response.getHeader('x-flash');
如有任何帮助,我们将不胜感激
最佳答案
你的模式是错误的。
"flash" is a session cookie它是通过调用 Action 创建的。你认为可以“检查闪现消息”的理论是行不通的。它们只会在对请求的响应中传递:
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
这意味着您需要通过 ajax 发送模式的表单请求,以便解析返回的数据(无论 x-flash
header 是否存在):
#modal
<%= form_tag ... remote: true do %>
#app/assets/javascripts/application.js
$(document).on("ajax:success", "#new_user_form", function(data, status, xhr) {
var flash = xhr.getHeader('x-flash');
if (flash) alert(flash);
});
要正确理解这一点,您应该阅读 stateless
properties of HTTP :
<小时/>An example of a stateless protocol is HTTP, meaning that each request message can be understood in isolation.
您需要的最重要的是flash.now
:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
after_filter :flash_headers, if: Proc.new {|c| c.request.xhr? }
private
def flash_headers
types = %i(error notice warning)
types.each do |type|
response.headers['x-flash'] = flash.now.send(type) unless flash.now[type].blank?
end
end
end
flash.now
将 flash 设置为针对该请求(默认情况下不作为新请求的一部分)。这将允许您通过 ajax 响应发送回值(对于 HTTP
来说,这是同一个请求)。
在“操作” Controller 中设置消息时,请记住使用 flash.now
:
#app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
flash.now[:notice] = "Success"
end
end
关于javascript - 是否可以检查 javascript (rails) 中是否存在 Flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005894/