繁体   English   中英

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

[英]Ruby/JS how to reload page after submit button?

我正在使用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 %>

我希望提交按钮起作用,并在刷新页面之前保存新创建的类别。 在代码中,页面在保存之前刷新。 请帮忙。 谢谢

你好那里在这种情况下你应该通过js ie提交表格

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

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

我更喜欢使用不引人注目的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 /categories的JS POST请求,此脚本都可以在任何页面上运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM