【问题标题】:Flash messages in Rails 3.2.3 and jsonRails 3.2.3 和 json 中的 Flash 消息
【发布时间】:2012-08-13 18:41:31
【问题描述】:

控制器中有一个动作。只能通过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=&gt;true 调用方法update

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

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

【问题讨论】:

    标签: ruby-on-rails ajax json ruby-on-rails-3.2


    【解决方案1】:

    为什么你的 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
    

    然后创建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>
    

    【讨论】:

    • 我问,如何显示json对象的flash消息?你回答关于js。
    • 完全糊涂了。如果你通过 Ajax 提交请求,它会响应 format.js 而不是 format.json,这只是一个 json 请求。
    • 如我所说,我需要处理一个json请求。
    • 这正是我需要的:)
    【解决方案2】:

    此帖子包含您需要的所有代码。它拯救了我的隐藏:

    https://gist.github.com/linjunpop/3410235

    这是它的一个分支,做了一些小的修改:

    https://gist.github.com/timothythehuman/5506787

    【讨论】:

      【解决方案3】:

      我认为 您必须绑定 ajax:success 回调,这将通过替换消息或将消息放置到 dom 来显示 Flash 消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-08
        • 1970-01-01
        • 2015-10-22
        • 2018-04-05
        • 1970-01-01
        • 2022-11-26
        • 2011-11-26
        相关资源
        最近更新 更多