您如何使用 Ajax 请求处理 Rail 的 flash? [英] How do you handle Rail's flash with Ajax requests?

查看:351
本文介绍了您如何使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆