【问题标题】:How to display a flash message on Rails using jQuery (SJR)如何使用 jQuery (SJR) 在 Rails 上显示 Flash 消息
【发布时间】:2016-11-07 05:10:20
【问题描述】:

我是 Web 开发和 jQuery 的初学者。

我希望在创建新消息时在屏幕上弹出一条闪现消息。使用下面的代码,创建时屏幕上会弹出一条新的聊天消息,而无需重新加载。但是,Flash 消息不会在创建聊天消息的同时出现。

有人知道如何处理这个问题吗?任何建议将不胜感激。

提前致谢!

我的母语不是英语,所以如果您有任何问题或这篇文章没有意义,请告诉我!

这是我的代码。

message/create.js.erb

$("#message_body").val("");
$("ul").html("<%=j(render @messages) %>");
$("#layout-notice").html("<%=j flash[:notice] %>");

messages_controller.rb

def index
  @messages = @chat_group.messages
  @message = Message.new
end

def create
  @message = Message.new(message_params)
  @message.chat_group = @chat_group
  @message.user = current_user
  # @message.save

  if @message.save
    flash[:notice] = 'successfully sent'
  else
    flash[:notice] = 'Unfortunately failed to sent'
  end

  @messages = @chat_group.messages.all
end

messasges/index.html.haml

 - if user_signed_in?
   = form_for @message, :url => {:action => :index}, remote: true do |f|
   = f.text_field :body
   = f.submit 'send'
  %ul
   = render @messages
   = link_to "sign out", destroy_user_session_path, method: :delete
  - else
   %h1 you need to log in
   = link_to "sign in", user_session_path, method: :post

【问题讨论】:

标签: javascript jquery ruby-on-rails ruby-on-rails-4


【解决方案1】:

闪光灯的工作原理

Rails flash 设置为允许您存储数据以供在下一个请求中使用(意味着在发生重定向并开始新的请求周期之后)。

来自Action Controller Overview - Ruby on Rails Guides

默认情况下,将值添加到闪存将使它们可用于下一个请求,但有时您可能希望在同一个请求中访问这些值...为此,您可以使用flash.now

当您使用 JS 响应时,请求完成后没有重定向。这意味着在 JS 请求期间将内容放入闪存将使其仅可用于下一个请求

所以,要在同一请求中使用 Flash 消息,您必须使用 flash.now

使用flash.now

您使用flash.now 的方式与普通闪存完全相同。

你的情况

if @message.save
  flash.now[:notice] = 'successfully sent'
else
  flash.now[:notice] = 'Unfortunately failed to sent'
end

其他资源

【讨论】:

  • 非常感谢您的小费,卡洛斯。但是,您建议的代码不起作用...您知道原因吗?
  • 当您说它不起作用时,您具体看到了什么?有错误信息吗? Flash 消息是否仍显示为空白?让我确切地知道您所看到的内容,我们可以进行调试。
  • 我很抱歉。 Flash 消息不会在消息创建的同时出现在屏幕上。
  • 尝试将其添加到您的 js.erb 文件的顶部:alert("&lt;%= j flash[:notice] %&gt;");,以便我们查看您的闪存是否设置正确。暂时删除除该警报之外的所有其他代码。
  • alert("&lt;%= j flash[:notice] %&gt;"); 正确显示,我的意思是,当创建新消息时。
猜你喜欢
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2011-07-05
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多