我试图让我的模式关闭,一旦一个新的位置被添加到它和用户按下提交按钮,但我似乎无法使它工作。我不知道我对.js做了什么是错的还是其他的。我是相当新的rails作为一个整体,这是我的第一个网站,所以任何帮助都是非常感谢的!谢谢!
理想情况下,它将关闭模式并刷新当前页面,以便在单击submit按钮时显示新位置。目前,它向DB提交位置,但我必须手动关闭模式并刷新页面以显示新位置。
这是我的位置index.html
<%= javascript_include_tag "form.js" %>
<%= link_to 'New Location', '#new_location_modal', 'data-toggle' => 'modal' %>
<div class="modal fade" id="new_location_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create new location</h4>
</div>
<div class="modal-body">
<%= render 'form', modal: true %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>_form.html.erb:
<% modal ||= false %>
<% remote = modal ? true : false %>
<%= form_for(@location, multipart: true, remote: remote, html: {role: :form, 'data-model' => 'location', id: 'new_loc_form'}) do |f| %>
<% if @location.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@location.errors.count, "error") %> prohibited this location from being saved:</h2>
<ul>
<% @location.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%# Added Bootstrap classes, and help-block container for error messages %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit 'Submit' %>
</div>
<% end %>form.js:
$('#new_loc_form').on('submit', function() {
$('#new_location_modal').modal('hide');
}):发布于 2015-07-06 18:05:09
如果您的目标是刷新页面,则不要在表单中设置remote: true。当表单提交时,控制器将调用重定向,页面将被刷新,模式也将被隐藏。
如果您需要处理remote表单提交,您的控制器应该能够respond_to一个js请求。
在您的控制器中:
def create
@location = Location.new(location_params)
#your logic here
respond_to do |format|
format.html { redirect_to locations_path } #or wherever you want to redirect
format.js {} #this will render create.js.erb
end现在,在您的create.js.erb中,您可以访问新创建的@location,在那里您可以将其附加到位置列表中,然后关闭模式。看一看这里的演示(最相关的是4分钟后开始的视频)。
https://stackoverflow.com/questions/31251649
复制相似问题