【问题标题】:Rails - How to submit a form without changing the page and updating the view?Rails - 如何在不更改页面和更新视图的情况下提交表单?
【发布时间】:2021-08-15 12:25:24
【问题描述】:

大家好!

我正在使用 rails 并且在我希望用户执行的步骤中(在同一页面上):

  1. 输入他的地址 Filling the form

  2. 提交表格 Click to submit

  3. 更新视图以显示地址 The view updated

我应该使用 Stimulis 还是 Ajax?我不太明白哪个更有用! 因为我尝试使用简单的 JS,但它不是 DRY 也不是很简单:

// file.js

document.querySelector(".form").addEventListener('submit', function () {
  adress_form = document.querySelector(".adress_form");
  adress_form.style.display="none";
  document.location.reload();
  display_adress = document.querySelector(".display_adress");
  display_adress.style.display = "block";
});
#file.html.erb

<div class="display_adress">
  <% if current_user.line1? && current_user.postal_code? && current_user.city? %>
    <p>Mon adresse actuel : <%= current_user.line1 %>, <%= current_user.city %> <%= current_user.postal_code %></p>
  <% end %>
</div>
<div class="address_form">
  <%= simple_form_for(current_user, remote: true, html: { id: "addddd"}) do |f| %>
  <%= f.input :line1, label: 'Mon adresse' %>
  <%= f.input :city, label: 'Ville' %>
  <%= f.input :postal_code, label: 'Code Postal' %>
  <%= f.submit %>
  <% end %>
</div>

要恢复,我希望用户在表单上输入他的地址、提交、更新我的数据库并使用用户提交的新地址更新视图

感谢您的帮助!

【问题讨论】:

    标签: javascript ruby-on-rails ajax stimulusjs


    【解决方案1】:

    您可以在控制器 javascript 中响应。例如: file.html.erb

    <%= simple_form_for(current_user, remote: true, format: :js, html: { id: "addddd"}) do |f| %>
    

    users_controller.rb

    def create
      # do your business logic
      render 'create
    end
    
    

    users/create.js.erb

    document.getElementById("formId").innerText = "Othe html text or you can call render(*)"
    
    

    【讨论】:

    • 非常感谢Деревянко Сергей!它可以工作,但是如果我想在另一个视图中使用另一个字段更新(或创建)我的用户,在 users/create.js.erb 中创建的 js 将再次被调用:/ 此外,当我手动刷新时,信息不是持久的页面...有解决该问题的方法吗? :)
    • 您想在传统后端制作动态前端(spa 页面、后端请求)。最佳实践是分别开发front(react、vue、angular等)和beckend(rest-api、graphql等)。在传统后端实现这样的操作非常困难和混乱,并且需要提供特殊的库(在 Rails 上反应或其他东西),如果你想对某一点提出类似的请求(例如更新用户),你应该在api_controllers
    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多