Ruby on rails 你如何处理铁路';使用Ajax请求的flash?
我很高兴我想到了这个。基本上,我有一个helper方法来内联重新加载flash,然后我有一个after_过滤器,如果请求是xhr,它会清除flash。有人有比这更简单的解决方案吗Ruby on rails 你如何处理铁路';使用Ajax请求的flash?,ruby-on-rails,ajax,Ruby On Rails,Ajax,我很高兴我想到了这个。基本上,我有一个helper方法来内联重新加载flash,然后我有一个after_过滤器,如果请求是xhr,它会清除flash。有人有比这更简单的解决方案吗 更新:上面的解决方案被写回Rails 1.x,不再受支持。我能想到的唯一改进是将page.reload\u flash设置为默认值(不必将其放在每个rjs文件中,如果不想重新加载flash,则将其设置为expicit,比如page.keep\u flash) 我不知道从哪里开始,但知道一些rails我肯定没那么难。看起
更新:上面的解决方案被写回Rails 1.x,不再受支持。我能想到的唯一改进是将page.reload\u flash设置为默认值(不必将其放在每个rjs文件中,如果不想重新加载flash,则将其设置为expicit,比如page.keep\u flash)
我不知道从哪里开始,但知道一些rails我肯定没那么难。看起来你需要的是
flash。现在[:注意]
,它只在当前操作中可用,在下一个操作中不可用。你可以在这里查看文档:这是js响应中需要的
如果您使用的是RSJ:
如果您使用的是jQuery:
$(“#flash_notice”).html(');
另一种方法是使用Ajax请求“OnFailure”处理程序的消息更新/显示“notice”div。它使您能够以所需效果显示这些flash消息。我使用了
render :text => "Some error happened", :status => 444
呈现:text=>“发生了一些错误”,:status=>444
在Javascript中
new AjaxRequest(...
,
OnFailure:function(transport) {
$("#notice").update(transport.responseText);
// show the message
}
);
新的AjaxRequest(。。。
,
OnFailure:功能(传输){
$(“#通知”).update(transport.responseText);
//显示消息
}
);
HTH您还可以使用after_过滤器块将flash消息存储在响应头中,并使用javascript显示它们:
class ApplicationController < ActionController::Base
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash[:error] unless flash[:error].blank?
# repeat for other flash types...
flash.discard # don't want the flash to appear when you reload page
end
用您自己的javascript flash函数替换alert(),或尝试jGrowl。基于gudleik答案:
class ApplicationController < ActionController::Base
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash_message
response.headers["X-Message-Type"] = flash_type
flash.discard # don't want the flash to appear when you reload page
end
private
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
end
end
def flash_type
[:error, :warning, :notice].each do |type|
return type unless flash[type].blank?
end
end
在控制器中按如下方式分配消息:
$(document).ajaxError(function(event, request) {
var msg = request.getResponseHeader('X-Message');
if (msg) alert(msg);
});
flash.now[:notice] = 'Your message'
app/views/layouts/application.js.erb-Ajax请求的布局。
在这里,您可以简单地使用
<%= yield %>
alert('<%= escape_javascript(flash.now[:notice]) %>');
警报(“”);
或者使用gritter制作一些丰富的动画:
$.gritter.add({
标题:‘--’,
文本:“”
});
建在其他建筑之上-
(我们将完整的flash对象作为JSON传递,使我们能够在浏览器中重建完整的flash对象。这可用于确保在Rails生成多条flash消息的情况下显示所有flash消息。)
我是这样做的
控制器:
查看:
<div id='notice'>
<%= render :partial => 'layouts/flash' , :locals => { :flash => flash } %>
</div>
respond_to :js
def your_ajax_method
flash[:notice] = 'Your message!'
end
'layouts/flash',:locals=>{:flash=>flash}%>
layouts/_flash.html.erb
<% flash.each do |name, msg| %>
<div class="alert-message info">
<a class="close dismiss" href="#">x</a>
<p><%= msg %></p>
</div>
<% end %>
$("#notice").html("<%= escape_javascript(render :partial => 'layouts/flash' , :locals => { :flash => flash }).html_safe %>");
post.js.erb
<% flash.each do |name, msg| %>
<div class="alert-message info">
<a class="close dismiss" href="#">x</a>
<p><%= msg %></p>
</div>
<% end %>
$("#notice").html("<%= escape_javascript(render :partial => 'layouts/flash' , :locals => { :flash => flash }).html_safe %>");
$(“#注意”).html('layouts/flash',:locals=>{:flash=>flash}).html_safe%>”;
有一个名为gem的工具,可以自动将flash消息编码到cookie中。客户端的javascript检查flash,并以您想要的任何方式显示它。这在普通和ajax请求中都能无缝工作 这是我基于@emzero的版本,对jQuery进行了修改,在Rails 3.2上进行了测试
应用程序\u controller.rb
我构建了一个引擎,其中包括一些行为到应用程序控制器,以便按照你们中的一些人的建议在响应头中发送flash消息
如果要使用AJAX调用,控制器中不应使用重定向到。相反,闪光信息应明确表示为: 在您的\u控制器中:
<div id='notice'>
<%= render :partial => 'layouts/flash' , :locals => { :flash => flash } %>
</div>
respond_to :js
def your_ajax_method
flash[:notice] = 'Your message!'
end
在由\u控制器中的\u ajax\u方法\u命名的视图中
controller.js.haml中的\u ajax\u方法
:plain
$("form[data-remote]")
.on("ajax:success", function(e, data, status, xhr) {
$('.messages').html("#{escape_javascript(render 'layouts/messages')}");
setTimeout(function(){ $(".alert").alert('close') }, 5000);
})
- flash.each do |name, msg|
- if msg.is_a?(String)
.alert-messages
%div{class: "alert alert-#{name == :notice ? "success" : "error"} fade in"}
%a.close{"data-dismiss" => "alert"}
%i.icon-remove-circle
= content_tag :div, msg, id: "flash_#{name}"
请注意,messages类是呈现消息的锚点。此类应该出现在视图或应用程序布局中。如果使用ERB,则该行变为$('.messages').html(“”)代码>
上述嵌入HAML/ERB的JavaScript是使用AJAX显示flash消息的关键。对于非AJAX调用,所有其他组件保持不变
您可以在_controller.js.coffee
或plain.js中使用您的_ajax_方法_,但是js/coffee将无法使用rails变量。尽管我在这里不使用变量,但我更喜欢用HAML包装JS以保持代码库的一致性
我利用Twitter引导设置消息样式,因此$(“.alert”).alert('close')
淡出通知。以下是部分信息:
layouts/_messages.html.haml
:plain
$("form[data-remote]")
.on("ajax:success", function(e, data, status, xhr) {
$('.messages').html("#{escape_javascript(render 'layouts/messages')}");
setTimeout(function(){ $(".alert").alert('close') }, 5000);
})
- flash.each do |name, msg|
- if msg.is_a?(String)
.alert-messages
%div{class: "alert alert-#{name == :notice ? "success" : "error"} fade in"}
%a.close{"data-dismiss" => "alert"}
%i.icon-remove-circle
= content_tag :div, msg, id: "flash_#{name}"
以防万一,下面是警报的CSS
.alert-messages {
position: fixed;
top: 37px;
left: 30%;
right: 30%;
z-index: 7000;
}
我修改了Victor的答案,以修复一些flash[type].blank?
不起作用的情况,正如评论中很少有人指出的那样
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash_message
response.headers["X-Message-Type"] = flash_type.to_s
flash.discard # don't want the flash to appear when you reload page
end
private
def flash_message
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return flash[type] unless flash[type].blank?
end
end
def flash_type
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return type unless flash[type].blank?
end
end
其余的都一样
// FLASH NOTICE ANIMATION
var fade_flash = function() {
$(".flash_notice").delay(5000).fadeOut("slow");
$(".flash_alert").delay(5000).fadeOut("slow");
$(".flash_error").delay(5000).fadeOut("slow");
};
var show_ajax_message = function(msg, type) {
$(".flash_message").html('<div class="flash_'+type+'">'+msg+'</div>');
fade_flash();
};
$( document ).ajaxComplete(function(event, request) {
var msg = request.getResponseHeader('X-Message');
var type = request.getResponseHeader('X-Message-Type');
show_ajax_message(msg, type); //use whatever popup, notification or whatever plugin you want
});
//FLASH通知动画
var fade_flash=函数(){
$(“.flash_notice”)。延迟(5000)。淡出(“慢”);
$(“.flash_alert”)。延迟(5000)。淡出(“慢速”);
$(“.flash_error”)。延迟(5000)。淡出(“慢”);
};
var show\u ajax\u message=函数(消息,类型){
$(“.flash_message”).html(“”+msg+“”);
淡入淡出闪光();
};
$(文档).ajaxComplete(函数(事件、请求){
var msg=request.getResponseHeader('X-Message');
var type=request.getResponseHeader('X-Message-type');
show_ajax_message(msg,type);//使用任何弹出窗口、通知或任何您想要的插件
});
这是我的版本(使用多个flash通知和特殊字符UTF-8编码):
内部应用程序控制器:
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
[:error, :warning, :notice].each do |type|
if flash[type]
response.headers["X-Ajax-#{type.to_s.humanize}"] = flash[type]
end
end
flash.discard
end
在我的咖啡脚本(twitter引导版本)中:
css\u类={
注意:'成功',
警告:‘警告’,
错误:“错误”
}
$(文档).ajaxComplete(事件、请求)->
对于输入[“通知”、“警告”、“错误”]
msg=request.getResponseHeader(“X-Ajax-#{type}”)
如果是味精?
$(“#通知”).append(“#{decodeURIComponent(escape(msg))}”)
此外,您可以存储消息类型:response.headers['X-message-type']=flash\u type
(而flash\u type返回最重要的类型(错误>成功>通知)。A
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash_message
response.headers["X-Message-Type"] = flash_type.to_s
flash.discard # don't want the flash to appear when you reload page
end
private
def flash_message
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return flash[type] unless flash[type].blank?
end
end
def flash_type
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return type unless flash[type].blank?
end
end
// FLASH NOTICE ANIMATION
var fade_flash = function() {
$(".flash_notice").delay(5000).fadeOut("slow");
$(".flash_alert").delay(5000).fadeOut("slow");
$(".flash_error").delay(5000).fadeOut("slow");
};
var show_ajax_message = function(msg, type) {
$(".flash_message").html('<div class="flash_'+type+'">'+msg+'</div>');
fade_flash();
};
$( document ).ajaxComplete(function(event, request) {
var msg = request.getResponseHeader('X-Message');
var type = request.getResponseHeader('X-Message-Type');
show_ajax_message(msg, type); //use whatever popup, notification or whatever plugin you want
});
after_filter :flash_to_headers
def flash_to_headers
return unless request.xhr?
[:error, :warning, :notice].each do |type|
if flash[type]
response.headers["X-Ajax-#{type.to_s.humanize}"] = flash[type]
end
end
flash.discard
end
css_class = {
Notice: 'success',
Warning: 'warning',
Error: 'error'
}
$(document).ajaxComplete (event, request) ->
for type in ["Notice", "Warning", "Error"]
msg = request.getResponseHeader("X-Ajax-#{type}")
if msg?
$('#notices').append("<div class=\"alert #{css_class[type]}\">#{decodeURIComponent(escape(msg))}</div>")