如何在我的页面顶部成功的ajax上显示flash消息而不刷新?

时间:2016-01-23 23:17:09

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

我的书签索引页面本质上是一个单页面应用程序。当我在页面底部提交新书签的表单时,我希望页面不必刷新并在页面顶部以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>

create中的bookmarks_controller方法:

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

我的bookmarks index.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中的flash消息处理不应该处理吗?可能是由于bookmark controller中的语法错误造成的? 我还有一个关于flash.now vs flash的问题。在这种情况下是否相关,因为书签提交是一个AJAX操作?

1 个答案:

答案 0 :(得分:1)

  

flash消息的形式

有可能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应该允许您相应地填充flash到Ajax:

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