How do you handle Rail#39;s flash with Ajax requests?(您如何使用 Ajax 请求处理 Rail 的 flash?)
问题描述
我对 解决方案很满意 我想出的.基本上,我有一个辅助方法可以重新加载内联闪存,然后我有一个 after_filter,如果请求是 xhr,则清除闪存.有人有比这更简单的解决方案吗?
I'm pretty happy with the solution that I came up with. Basically, I have a helper method that reloads the flash inline, and then I have an after_filter that clear out the flash if the request is xhr. Does anyone have a simpler solution than that?
更新:上面的解决方案是在 Rails 1.x 中写回的,不再受支持.
Update: The solution above was written back in Rails 1.x and is no longer supported.
推荐答案
您还可以使用 after_filter 块将 flash 消息存储在响应标头中,并使用 javascript 显示它们:
You can also store the flash messages in the response headers using a after_filter block and display them using 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
在 application.js 中添加一个全局 ajax 处理程序.对于 jquery,请执行以下操作:
And in application.js add a global ajax handler. For jquery do something like this:
$(document).ajaxError(function(event, request) {
var msg = request.getResponseHeader('X-Message');
if (msg) alert(msg);
});
用您自己的 javascript flash 函数替换 alert() 或尝试 jGrowl.
Replace alert() with your own javascript flash function or try jGrowl.
这篇关于您如何使用 Ajax 请求处理 Rail 的 flash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您如何使用 Ajax 请求处理 Rail 的 flash?


基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06