2014-09-02 63 views
0

我想表明在成功AJAX更新Flash成功通知,通常我顯示通過由動作閃光燈通知,觸發閃光燈通知 - Ruby on Rails的

def something 

    redirect_to "that_controller_path", :notice => "Success" 

end 

但是我有沒有線索至於如何做到這一點的AJAX調用成功,我的Ajax調用,

$.ajax(
     { 
     type: "POST", 
     url: path, 
     data: response1, 
     contentType: "application/json", 
     success: -> 

       window.location.replace(window.location.protocol + "//" + 
             window.location.host + "/configuration/manage_users") 
       #Something here! 


     }); 

閃光燈通知是在我的應用程序視圖,

<%if flash[:notice]%> 
    <div class="flash_notice"> 
     <%=flash[:notice]%><br> 
    </div><!-- close --> 
<%end%> 

回答

0

阿賈克斯

首先,我要解釋一下,你無法通過「標準」的Ajax流量通過標準flash功能。原因是作爲flash is set in a session cookie,你只能用瀏覽器刷新訪問這些:

閃光燈是一個與每個 請求清除會話的一個特殊部分。這意味着存儲的值只會在 可接下來的請求,這是用於傳遞錯誤信息等有用

你需要enure當您發送/接收阿賈克斯,以設置flash消息,你必須以不同的方式照顧他們;通過ajax調用本身,或通過其他方法。

-

誠然,我從來沒有這樣做過,但看着這個答案建議你可以set the headers在你的Ajax調用:

#app/controllers/your_controller.rb 
class YourController < ApplicationController 
    after_action :flash_headers 

    def flash_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 you reload page 
    end 

    private 

    def flash_message 
     [:error, :warning, :notice, nil].each do |type| 
     return "" if type.nil? 
     return flash[type] unless flash[type].blank? 
     end 
    end 

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

我解除從這個答案代碼:How do you handle Rail's flash with Ajax requests?

這設置個標題您的要求,讓你通過你的JS拉這樣的數據:

#app/assets/javascripts/application.js.coffee 
$(document).on "click", "a", -> 
    $.ajax 
     type: "POST", 
     url: path, 
     data: response1, 
     contentType: "application/json", 
     success: (data) -> 
     msg = request.getResponseHeader('X-Message') 
     type = request.getResponseHeader('X-Message-Type') 

     alert msg #should alert the flash message 

如果一切正常,它會給你設置&顯示flash消息,你想

0

在容量我情況下,我使用gritter來顯示不錯的通知。

所以在我的application.html.erb我有我的產量前:

<div id="flash"> 
    <%= render partial: "shared/notice_banner" %> 
</div> 

在這部分,我有:

<% flash.each do |key, message| %> 
    <%= js add_gritter(message, :title => key.titleize, sticky: false, time: 3000, :image => key) %> 
<% end %> 

在我的控制器:

flash.now[:notice] = "Movie has been deleted." 

respond_to do |format| 
    format.html { redirect_to root_path } 
    format.js 
end 

和最後在我的method.js中。ERB:

$("#flash").html('<%= j render partial: "shared/notice_banner" %>') 

你可以看到整個代碼在這裏:

https://github.com/cristofer/moviedb

我希望它能幫助

乾杯