【问题标题】:Rails: How to print error message with Ajax Jquery?Rails:如何使用 Ajax Jquery 打印错误消息?
【发布时间】:2013-08-04 12:38:49
【问题描述】:

目前,这是我用于创建新消息的代码:

  if @message.save
    respond_to do |format|
      format.html { redirect_to messages_path }
      format.js
    end
  else
    flash[:notice] = "Message cannot be blank!"
    redirect_to :back
  end

如何在 Ajax 中打印相同的消息?还想控制它的格式和位置。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 jquery


    【解决方案1】:

    应用控制器

      after_filter :add_flash_to_header
    
      def add_flash_to_header
        # only run this in case it's an Ajax request.
        return unless request.xhr?
    
        # add different flashes to header
        response.headers['X-Flash-Error'] = flash[:error] unless flash[:error].blank?
        response.headers['X-Flash-Warning'] = flash[:warning] unless flash[:warning].blank?
        response.headers['X-Flash-Notice'] = flash[:notice] unless flash[:notice].blank?
        response.headers['X-Flash-Message'] = flash[:message] unless flash[:message].blank?
    
        # make sure flash does not appear on the next page
        flash.discard
      end
    

    将通知代码移动到部分:

    <div class="noticesWrapper">
      <% flash.each do |name, msg| %>
        <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
          <a class="close" data-dismiss="alert"><i class="icon-remove"></i></a>
          <%= msg %>
        </div>
      <% end %>
    </div>
    

    js.erb 文件中:

    $('.noticesWrapper').html("&lt;%= j(render partial: 'layouts/flash_notices') %&gt;");

    在控制器操作中,您需要使用 flash.now 来闪烁消息:

    flash.now[:error] = "your message"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多