【问题标题】:Flash Notice on Ajax Success Rails关于 Ajax Success Rails 的 Flash 通知
【发布时间】:2014-05-08 05:43:46
【问题描述】:

在某些情况下,我试图在我的 html 页面中获取一条 Flash 消息。我是 Ruby 新手,我不知道如何完成这项工作。

这是我的控制器

     if @item_point > current_user.points
        flash[:alert] = "You don't have enough points to buy this item"
      else
      end
      respond_to do |format|
        format.html {redirect_to '/hhr'}
        format.js
      end 

在我的脚本中,我试图在我的 ajax 成功函数中获取它。但我无法获取它。有什么方法可以在我的 jquery 函数中或在我的视图中获取此 Flash 消息. 请帮忙。 提前致谢

【问题讨论】:

  • 发布您的script code
  • 添加相关的脚本和Html代码,在哪里显示flash信息。

标签: jquery ruby-on-rails ruby ajax


【解决方案1】:

参考下面的代码。它可能会帮助你

#inside your rails controller method  
flash[:notice] = "Your Notice content to be displayed"



#rails helper
module ApplicationHelper
  def flash_notifications
    message = flash[:error] || flash[:notice]

    if message
      type = flash.keys[0].to_s
      javascript_tag %Q{$.notification({ message:"#{message}", type:"#{type}" });}
    end
  end

end



#rails layout
<%= flash_notifications -%>



#javascript code
(function( $, undefined ) {
    $.notification = function(options) {
        var opts = $.extend({}, {type: 'notice', time: 3000}, options);
        var o    = opts;

        timeout          = setTimeout('$.notification.removebar()', o.time);
        var message_span = $('<span />').addClass('jbar-content').html(o.message);
        var wrap_bar     = $('<div />').addClass('jbar jbar-top').css("cursor", "pointer");

    if (o.type == 'error') {
          wrap_bar.css({"color": "#D8000C"})
        };

        wrap_bar.click(function(){
            $.notification.removebar()
        });

        wrap_bar.append(message_span).hide()
            .insertBefore($('.container')).fadeIn('fast');
    };


    var timeout;
    $.notification.removebar    = function(txt) {
        if($('.jbar').length){
            clearTimeout(timeout);

            $('.jbar').fadeOut('fast',function(){
                $(this).remove();
            });
        }   
    };


})(jQuery);

【讨论】:

    【解决方案2】:

    你应该看看这个:

    Jquery AJAX: How to display the Flash error message when validation on the server side fails?

    建议您从 Rails 应用程序返回 HTML 错误状态,然后您可以在 Ajax 'error' 回调中添加 flash[:alert]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      相关资源
      最近更新 更多