【问题标题】:How to display flash messages, on successful ajax, at the top of my page, without refreshing?如何在成功的ajax上在我的页面顶部显示flash消息而不刷新?
【发布时间】:2016-04-30 10:28:42
【问题描述】:

我的书签索引页本质上是一个单页应用程序。当我在页面底部提交新书签的表单时,我希望页面不必刷新并在页面顶部以 Flash 消息的形式显示 "Bookmark successfully created!"

在我的 application.html.erb 文件中,我正在渲染 Flash 消息:

<!DOCTYPE html>
<html>
<head>
  <title>Text Me Later</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= render partial: 'layouts/nav' %>

<% flash.each do |key, value| %>
  <% if key == "notice" %>
    <%= content_tag :div, value, class: "text-center alert alert-warning" %>
  <% elsif key == "alert" %>
    <%= content_tag :div, value, class: "text-center alert alert-danger" %>
  <% else %>
    <%= content_tag :div, value, class: "text-center alert alert-success" %>
  <% end %>
<% end %>

<div class="container">

<%= yield %>

<%= debug(params) if Rails.env.development? %>

</body>
</html>

我的bookmarks_controller中的create方法:

def create
    @bookmark = Bookmark.new bookmark_params
    @bookmark.user_id = current_user.id

    respond_to do |format|
      if @bookmark.save
        flash[:notice] = 'Bookmark was successfully created.'
        format.html { 
          redirect_to user_bookmarks_path
        }
        format.json { 
          render json: @bookmark,
          status: :created, 
          location: @bookmark
        }
        format.js {}
      else
        flash[:error] = "Bookmark could not be created."
        format.html {
          render :index
        }
        format.json {
          render json: @bookmark.errors.full_messages
        }
        format.js {}
      end
    end
  end

我的bookmarksindex.html.erb文件:

<h2>All of <%= current_user.first_name %>'s Bookmarks</h2>
<ul id="all-bookmarks">
    <% @bookmarks.each do |bookmark| %>
    <li class="bookmark-div">
            <div><%= bookmark.title %></div>
            <div><%= bookmark.image %></div>
            <div><%= bookmark.description %></div>
            <div><%= bookmark.location %></div>
            <div><%= bookmark.time %></div>
            <div><%= bookmark.date %></div>
            <div><%= bookmark.created_at %></div>
            <div><%= bookmark.updated_at %></div>
            <div><%= bookmark.url %></div>
            <div><%= link_to "Edit", [:edit, bookmark]%></div>
            <div><%= link_to "Delete Bookmark", bookmark, :method => :delete, confirm: 'are you sure?'%></div>
            <div><%= link_to "Add as a reminder" %></div>
    </li>
    <% end %>
</ul>

<h2>Add a bookmark below:</h2>

    <div id="post-new-bookmark">
        <%= simple_form_for [@user, @bookmark], :method => :post, remote: true do |f| %>
            <% if @bookmark.errors.any? %>
             <div id="errorExplanation">
              <h2><%= pluralize(@bookmark.errors.count, "error") %> prohibited this post from being saved:</h2>
              <% end %>
            <%= f.input :title %>
            <%= f.input :image %>
            <%= f.input :description %>
            <%= f.input :location %>
            <%= f.input :date %>
            <%= f.button :submit %>
        <% end %>
    </div>

create.js.erb:

$("<%= escape_javascript(flash[:notice]) %>").appendTo("#flash-notice")

$("<%= escape_javascript render(:partial => 'bookmarks/cbookmark', :locals => { :bookmark => @bookmark }) %>").appendTo("#all-bookmarks")

我的问题是:为什么在成功创建书签后没有立即显示在页面顶部的 Flash 消息?我的application.html.erb中的闪存消息处理不应该处理它吗?可能是因为我的bookmark controller 中有语法错误吗? 我还有一个关于 flash.now 与 flash 的问题。由于书签提交是 AJAX 操作,因此在这种情况下是否相关?

【问题讨论】:

    标签: javascript ruby-on-rails ajax flash error-handling


    【解决方案1】:

    短信形式

    Ce ne pas possible avec le flash de Rails

    --

    Flash 是 Rails 在操作之间填充的 session cookie 的一部分。众所周知,这很难用 Ajax 解析,并且确实仍然是一个难以实现的模式(当您的浏览器没有刷新时,Rails 如何重新填充session)。

    解决方法是使用flash.now 通过您的ajax 方法传递值。 Good ref here(我写过):

    #app/controllers/bookmarks_controller.rb
    class BookmarksController < ApplicationController
       def create
        @bookmark = Bookmark.new bookmark_params
        @bookmark.user_id = current_user.id
    
        respond_to do |format|
          if @bookmark.save
            flash.now[:notice] = 'Bookmark was successfully created.'
            format.html { redirect_to user_bookmarks_path }
            format.json { render json: @bookmark, status: :created, location: @bookmark }
            format.js
          else
            flash.now[:error] = "Bookmark could not be created."
            format.html { render :index }
            format.json { render json: @bookmark.errors.full_messages }
            format.js
          end
        end
      end
    end
    

    使用flash.now 应该允许您通过Ajax 相应地填充flash

    #app/views/bookmarks/create.js.erb
    $("<%=j flash.now[:notice]  %>").appendTo("#flash-notice")
    

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2021-09-30
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多