长话短说,我有一个按钮。在单击它时,我希望触发一个ajax请求,该请求将获取flash [:notice]并将其显示在div in $中
这是我的简短 View :
<input type="button" id="search" value="display"/>
<div id="notice">
</div>
我在 View 中的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;
});
我的 Controller :
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" %>");
问题是当我单击按钮时,通知显示良好。但是,同样的注意仍然存在于下次点击上。搜索部分包含该表请帮助!
最佳答案
这是我工作的一个例子,这要感谢Rich Peck的回答。我需要使用flash.now
来确保闪存通知不会持续存在。
View 中的AJAX触发器:
<%= link_to "Email report", users_path, remote: true %>
Controller :
# 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
渲染 View :
# app/views/users/index.js.erb
$("#flash").html('<%= j render partial: "shared/notice_banner" %>');
在布局中显示Flash通知的位置:
# 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">×</a>
</div>