gpt4 book ai didi

ruby-on-rails - Rails 3.2.3 和 json 中的 Flash 消息

转载 作者:行者123 更新时间:2023-12-04 06:14:48 25 4
gpt4 key购买 nike

Controller 中有一个 Action 。只能通过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

页面的一部分

<% unless flash[:error].blank? %>
<%= flash[:error] %>
<% end %>

<% unless flash[:message].blank? %>
<%= flash[:notice] %>
<% end %>
<!-- page content goes -->

当然,一个页面包含一个 button_to 并且 :remote=>true 调用方法 update

最重要的是,更新后它什么也没显示。 JSON 对象肯定会返回,我可以在 fireBug 中看到它。

问题是,我是否正确使用了闪光灯?我如何使用它在页面上显示消息?请不要忘记 ajax。

最佳答案

为什么你的 respond_to block 中有 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

然后创建update.js.erb

$("#notice").text("<%= escape_javascript(flash[:notice]) %>")
$("#notice").show()

上面的代码可能不是 100% 正确。

对于 flash,我有类似的东西:

<div id="notice">
<% flash.each do |key, value| %>
<%= content_tag(:div, value, :class => "flash #{key}") %>
<% end %>
</div>

关于ruby-on-rails - Rails 3.2.3 和 json 中的 Flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com