我的書籤索引頁面本質上是一個單頁面應用程序。當我在頁面底部提交新書籤的表單時,我希望頁面不必刷新,並以頁面頂部的Flash消息的形式顯示"Bookmark successfully created!"
。如何在頁面頂部顯示成功的ajax上的Flash消息而不刷新?
在我application.html.erb
文件,我渲染的提示信息:
<!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")
我的問題是:爲什麼在成功的書籤作成閃光燈消息不是頁面右側的頂部成功創建後顯示?我的application.html.erb
中的閃光消息處理不應該照顧它嗎?這可能是由於我的bookmark controller
中的語法錯誤嗎? 我也有一個關於flash.now vs flash的問題。在這種情況下,書籤提交是AJAX操作嗎?