2016-01-26 51 views
1

我在我的主頁(使用設計)上使用自定義註冊模式,並且我使用flash來存儲錯誤並在自定義註冊中顯示它們模態。我想知道的是,我是否可以使用JavaScript檢查Flash中是否有消息,如果有,我可以在重定向到主頁時自動打開模式。因此,基本上,我需要的JavaScript可以做到以下幾點:是否有可能檢查在JavaScript(導軌)中是否存在flash消息

Are there messages stored using flash? 
If so, open modal when homepage loads. 

使用JS網頁加載時我已經可以開模,但我不能工作了如何檢查是否有提示信息。是否可以訪問閃存並檢查是否存在使用js存儲的任何錯誤?謝謝!

編輯:

所以我完全新的AJAX,但我也跟着這樣的:http://ashleyangell.com/2010/10/handling-rails-flash-message-with-ajax-requests/

添加以下到我的應用程序控制器:

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'); 

任何幫助,將不勝感激

+0

使得Ajax請求。根據回覆打開模式 – charlietfl

+0

看起來像什麼? – chris

+0

不難做谷歌搜索它。不會有任何問題尋找教程寶石等 – charlietfl

回答

1

你的模式是錯誤的。

"flash" is a session cookie它是通過調用一個動作而創建的。你可以「檢查閃光信息」的理論不起作用。它們僅在對請求的響應中遞送:

閃光燈是會話的特殊部分,每次請求都會清除它。這意味着存儲在那裏的值將在接下來的請求,這是用於傳遞錯誤信息等

這意味着你需要通過AJAX發送您的模態的形式要求,以解析返回的數據有用的,只有用(不管x-flash頭是否存在與否):

#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

無國籍PROT的例子ocol是HTTP,這意味着每個請求消息都可以被孤立地理解。


你需要最重要的事情是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進行閃光燈的存在爲請求(而不是默認的新請求的一部分)。這將允許您通過您的ajax響應(其中,HTTP,是相同的請求)發回數值。

記得在你的「行動」控制器設置消息時使用flash.now:對於

#app/controllers/sessions_controller.rb 
class SessionsController < ApplicationController 
    def create 
     flash.now[:notice] = "Success" 
    end 
end 
+1

非常感謝,這是超級有用! – chris

0

它看起來像你使用jQuery作出AJAX調用。我想你需要一些JS,看起來像這樣

$(document).load(function(){ 
    $.ajax('/url/of/action') 
    .done(function(data, textStatus, request){ 
     var flash = request.getResponseHeader('x-flash'); 
     if (flash) alert(flash); 
    }); 
}); 

將調用/url/of/action它完成時看標題爲x-flash頭。

+0

嗯我無法讓它工作。我沒有試圖調用另一個url,我只是想從創建文檔 – chris

+0

@chris的原始url中獲得頭文件,你必須弄清楚什麼叫原始url和JS。除了通過原始請求之外,沒有辦法獲取標題。 –

相關問題