您如何使用 Ajax 请求处理 Rail 的 flash?

2022-01-31 00:00:00 ruby-on-rails ajax

我对 解决方案很满意 我想出的.基本上,我有一个辅助方法可以重新加载内联闪存,然后我有一个 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.

相关文章