Jquery 通过AJAX-RubyonRails成功更新时触发flash通知

Jquery 通过AJAX-RubyonRails成功更新时触发flash通知,jquery,ruby-on-rails,ajax,Jquery,Ruby On Rails,Ajax,我想在成功的AJAX更新后显示flash成功通知,通常我通过以下操作显示flash通知: def something redirect_to "that_controller_path", :notice => "Success" end 但是我不知道如何在AJAX成功调用中实现这一点,我的AJAX调用是 $.ajax( { type: "POST", url: path, data: response1, cont

我想在成功的AJAX更新后显示flash成功通知,通常我通过以下操作显示flash通知:

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!


      });
flash通知在我的应用程序视图中显示为

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

首先,我需要解释,不能通过标准Ajax流传递标准flash功能。原因是,作为,您只能通过浏览器刷新来访问这些文件:

闪存是会话的一个特殊部分,每个会话都会清除闪存 要求这意味着存储在那里的值只能在中使用 下一个请求,用于传递错误消息等

您需要确保,当您发送/接收ajax时,为了设置flash消息,您必须以不同的方式满足它们;要么通过ajax调用本身,要么通过另一种方法

-

标题

诚然,我以前从未这样做过,但看看这个答案,您可以在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

如果这样做有效,它将使您能够按照自己的意愿设置和显示flash消息

在我的情况下,我使用gritter显示漂亮的通知

因此,在我的application.html.erb中,我的收益率之前:

<div id="flash">
  <%= render partial: "shared/notice_banner" %>
</div>
最后在我的method.js.erb中:

$("#flash").html('<%= j render partial: "shared/notice_banner" %>')
您可以在此处看到整个代码:

我希望有帮助

干杯

<% 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
$("#flash").html('<%= j render partial: "shared/notice_banner" %>')