长话短说,我有一个按钮。单击它时,我希望触发一个 ajax 请求,该请求获取 flash[:notice] 并将其显示在 $
中的 div 中这是我的简短 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" %>");
问题是当我单击按钮时,通知显示正常。但下次点击时也会出现同样的通知。搜索部分包含表 Please help!
最佳答案
这是我工作的一个例子,感谢 Rich Peck 的回答。我需要使用 flash.now
来确保 Flash 通知不会持续存在。
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>
关于javascript - Rails 通过 ajax 发出闪光通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967390/