在某些情况下,我试图在我的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成功功能。但是我找不到……是否有任何方法,我可以得到这个flash消息在我的jquery函数或在我的视图。请帮助。提前感谢
参考下面的代码。它可能对你有帮助
#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);
你应该看看这个:
Jquery AJAX:当服务器端验证失败时如何显示Flash错误信息?
它建议从Rails应用程序返回一个HTML错误状态,然后你可以在Ajax 'error'回调中添加flash[:alert]。