首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >通过ajax发布Rails flash通知

通过ajax发布Rails flash通知
EN

Stack Overflow用户
提问于 2014-05-31 15:04:05
回答 1查看 47.3K关注 0票数 31

长话短说,我有一个按钮。单击它时,我希望触发一个ajax请求,该请求将获得flash:notice并将其显示在$的div中

以下是我的简短观点:

 <input type="button" id="search" value="display"/>

 <div id="notice">

 </div>

我在视图中的ajax请求:

$("#search").submit(function(){
                            $.ajax({
                                type: "POST",
                                url: //url to my show action
                                success: function(data){
                                      /*$("#notice").html("<%= flash[:notice] %>");
                                        $("#content").html(data);*/
                                }
                            });
                            return false;
                    });

我的控制器:

def HomeController <  ActionController::Base
  def index

  end

  def show
    respond_to do |format|
    format.js {  flash[:notice] = "" + count.to_s + " results found for " + params[:query][:search_key] + "" }
    end
    #render :partial => 'search'
  end
end

我的show.js.erb

#app/views/dashboard_home/show.js.erb
$("#notice").html("<%=j flash[:notice] %>");

$("#content").html("<%=j render partial: "search" %>");

问题是当我点击按钮时,通知显示得很好。但在下一次点击时,同样的通知也会持续存在。搜索部分包含表请帮助!

EN

回答 1

Stack Overflow用户

发布于 2015-01-07 09:41:07

多亏了Rich Peck的回答,这是我工作的一个例子。我需要使用flash.now来确保闪光通知不会持续存在。

视图中的AJAX触发器:

<%= link_to "Email report", users_path, remote: true %>

控制器:

# app/controllers/users_controller
class UsersController < ApplicationController

  def index
    # do some things here

    respond_to do |format|
      format.js { flash.now[:notice] = "Here is my flash notice" }
    end
  end
end

渲染视图:

# app/views/users/index.js.erb
$("#flash").html('<%= j render partial: "shared/notice_banner" %>');

在布局中显示闪光通知的位置:

# app/views/layouts/application.html.erb
<div id="flash">
  <% if notice.present? %>
    <%= render partial: "shared/notice_banner" %>
  <% end %>
</div>


# app/views/shared/_notice_banner.html.erb
<div data-alert class="alert-box">
  <%= notice %>
  <a href="#" class="close">&times;</a>
</div>
票数 32
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23967390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档