[英]Flash messages in Rails 3.2.3 and json
There is an action in a controller. 控制器中有一个动作。 It can be called only with json format via ajax . 它只能通过ajax以json格式调用。
def update
@article = Article.find_by_id params[:id]
respond_to do |format|
if @article.update_attributes(params[:article])
flash[:message] = "good"
else
flash[:error] = @article.errors.full_messages.join(", ")
end
format.json { render :json => flash}
end
end
the part of a page 页面的一部分
<% unless flash[:error].blank? %>
<%= flash[:error] %>
<% end %>
<% unless flash[:message].blank? %>
<%= flash[:notice] %>
<% end %>
<!-- page content goes -->
Of course, a page contains a button_to
with :remote=>true
that calls the method update
. 当然,页面包含一个button_to
其中:remote=>true
,用于调用方法update
。
The bottom line is that it shows nothing after updating. 底线是更新后没有显示任何内容。 JSON object definitely returns, I can see it in fireBug. JSON对象肯定会返回,我可以在fireBug中看到它。
The question is, am I using flash correctly? 问题是,我正确使用闪光灯吗? And how do I use it to show a message on a page? 我如何使用它在页面上显示消息? Please don't forget about ajax. 请不要忘记ajax。
Why do you have an if/else statement in your respond_to block? 为什么在respond_to块中有if / else语句?
def update
@article = Article.find_by_id params[:id]
if @article.update_attributes(params[:article])
flash[:notice] = "Good"
else
flash.now[:notice] = "Bad"
render "edit"
end
respond_to do |format|
format.html {redirect_to @article}
format.js
end
end
Then create update.js.erb 然后创建update.js.erb
$("#notice").text("<%= escape_javascript(flash[:notice]) %>")
$("#notice").show()
Code above might not be 100% correct. 上面的代码可能不是100%正确。
For flash, I'd have something like: 对于闪存,我会有类似的东西:
<div id="notice">
<% flash.each do |key, value| %>
<%= content_tag(:div, value, :class => "flash #{key}") %>
<% end %>
</div>
This posting has all the code you'll need. 此帖子包含您需要的所有代码。 It saved my hide: 它保存了我的隐藏:
https://gist.github.com/linjunpop/3410235 https://gist.github.com/linjunpop/3410235
Here's a fork of it that makes a few minor modifications: 这是它的一个分支,它做了一些小修改:
https://gist.github.com/timothythehuman/5506787 https://gist.github.com/timothythehuman/5506787
我认为你必须绑定ajax:success
回调,它将通过替换消息或将消息发送到dom来显示flash消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.