如何在提交按钮后重新加载Ruby/JS页面?

5

我正在使用Ruby on Rails编写Web应用程序。 在控制器中:

  def create
@category = Category.new(category_params)

respond_to do |format|
  if @category.save
    format.html { redirect_to @category, notice: 'Category was successfully created.' }
    format.json { render :show, status: :created, location: @category }
    format.js { render js: 'window.top.location.href = "/categories";' }
  else
    format.html { render :new }
    format.json { render json: @category.errors, status: :unprocessable_entity }
  end

end

在 new.html.erb 文件中:

<h1>New category</h1>
<%= render 'form' %>
<%= link_to 'Back', categories_path %>

在_form.html.erb文件中:
<%= form_for(@category) do |f| %>
<% if @category.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>
  <ul>
  <% @category.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content, placeholder: "content" %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description, placeholder: "description" %>
</div>
<div class="actions">
<a href="#" onclick="window.top.location.reload(true)"><%= f.submit  %>
</a>
</div>
<% end %>

我希望提交按钮能够正常工作,并且在页面刷新之前保存新创建的类别。在代码中,页面在保存之前已经被刷新。 请帮忙。谢谢。

1
删除 onclick="window.top.location.reload(true)" - madalinivascu
2个回答

4
我喜欢使用不显眼的JavaScript。因此,我的答案如下:
_form.html.erb
<%= form_for(@category, remote: true) do |f| %>
  ...
  <div class="actions">
    <%= f.submit %>
  </a>
</div>
<% end %>

categories_controller.rb

def create
  @category = Category.new(category_params)

  respond_to do |format|
    if @category.save
      format.html { redirect_to @category, notice: 'Category was successfully created.' }
      format.json { render :show, status: :created, location: @category }
      format.js { render js: 'window.top.location.reload(true);' }
    else
      format.html { render :new }
      format.json { render json: @category.errors, status: :unprocessable_entity }
    end
  end
end

请注意,我已更新format.js以呈现一个JS脚本,该脚本会重新加载页面,如你所需。但是,你应该知道,这个脚本将在任何页面上起作用,只要在那个页面上调用了一个JS POST请求到/categories

3

你好,在这种情况下,你应该通过js提交表单,即:

<%= form_for(@category, remote: true) do |f| %>
<%= end%>

如果有任何问题,请告诉我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接