【问题标题】:How to submit form and update element on the page without refresh, in Rails 4在 Rails 4 中,如何在不刷新的情况下在页面上提交表单和更新元素
【发布时间】:2014-05-06 21:32:22
【问题描述】:

我在尝试做一些我认为相当简单的事情时遇到了很多麻烦。

我有一个项目列表,比如说待办事项。在该列表的底部,我有一个文本字段,可在其中向该列表添加新项目。我想让新项目动态添加到该列表的底部,而无需刷新整个页面,就像在聊天窗口中一样。

我制作了提交表单remote: true,它在不重新加载页面的情况下成功提交,但我无法让新项目同时出现在列表底部。我必须刷新页面才能看到更改。

我尝试了一些我在 SO(这里不乏类似问题)和网络上找到的不同方法,甚至还有一个名为 Sync 的 gem,但每个方法都有自己的错误和问题,我无法理解任何正常工作。他们每个人都可能是自己的 SO 问题。所以我问:是否有一个“秘诀”可以确保在 Rails 4 中成功实现这一点?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4


    【解决方案1】:

    假设现在您有一个用户表单要提交,

    <%=form_for @user,remote: true%><%end%>
    

    你还有一个控制器,

    UsersController
    

    在你的控制器中,你有一个函数,

    def create
      #something
    end
    

    用于表单。

    你唯一需要做的就是修改函数

    def create
      #something
      respond_to do |format|
        format.js
        format.html
      end
    end
    

    然后在你的视图侧,在 view/users/ 目录下,创建一个 create.js 文件,在该文件中,你可以做 js 动作,比如获取新记录,并将新记录追加到用户列表中.

    参考:

    http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#form-for

    【讨论】:

    • 能否提供一个示例链接。
    • form_for 现在已软弃用。 form_with 最好在 2021 年使用 来源:guides.rubyonrails.org/…
    【解决方案2】:

    有多种方法可以满足您的要求。我的方法是:

    • 创建一个AJAX调用到传递表单参数的控制器

    • 在控制器内部,您保存/更新内容,然后返回JSON 对象

    • AJAX 函数的success 回调中,使用对象值追加列表项/表格行

    代码可能是这样的:

    model.js

    $(function() {
      $("#submit_button").on("click", function(event) {
        event.preventDefault();
        $.ajax({
          type: "POST",
          url: "your_controller_url",
          data: "your_form_data"
          success: function(result) {
            // Append the result to a table or list, $("list").append(result)
          },
        });
      });
    });
    

    controller.rb

    def your_action
      # Do your stuff
      # return JSON to the ajax call
    end
    

    嗯,这只是一个骨架。我更喜欢以这种方式做事。 (因为我讨厌 js.erb 方法)

    【讨论】:

      【解决方案3】:

      这是 rails 5,希望对某人有所帮助(它仍然适用于 rails 4):

      试试这个 ajax 示例:

      在'routes.rb'中:

      # set the route that ajax can find the path to what controller in backend
      get   '/admin/some_great_flow',   to: 'great_control#great_flow'
      

      在“great_control_controller.rb”控制器中:

       # this function in controller will response for ajax's call
       def great_flow
          # We can find some user or getting some data, model here.
          # 'params[:id]' is passed by ajax that we can use it to find something we want.
          @user = User.find(params[:id]) 
      
          # print whole data on terminal to check it correct.
          puts YAML::dump(@user.id) 
      
          # transform what you want to json and pass it back.        
          render json: {staff_info: @user } 
      end
      

      在“app/views/great_control/index.html.erb”视图中:

      <div>
           <label>Staffs</label>
           <%=select_tag(:staff, options_from_collection_for_select(@staffs, :id, :name), id:"staff_id", required: true)%>
      </div>
      <script>
      //every time if option change it will call ajax once to get the backend data.
      $("#staff_id").change(function(event) {
          let staff_id = $("#staff_id").val()
          $.ajax({
              // If you want to find url can try this 'localhost:prot/rails/info/routes'
              url: '/admin/some_great_flow', 
              type: 'GET',
              dataType: 'script',
              data: { id: staff_id },
              // we get the controller pass here
              success: function(result) {
                   var result = JSON.parse(result);
                   console.log(result['staff_info']);
                   // use the data from backend for your great javascript.
              },
          });
      });
      </script>
      

      我自己写的。

      【讨论】:

        【解决方案4】:

        您可以使用 javascript 查看更改。 例如,让我们考虑一个带有动作索引的控制器 Mycontroller 并且您正在提交索引上的表单。 然后在视图 my_controller/index.js.erb 中创建一个文件

        要反映更改,请在此模板中使用 javascript。 肯定是远程发送 ajax 调用,因此要查看更改,您需要使用 javascript 进行一些操作。

        谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-15
          • 1970-01-01
          • 2011-10-17
          • 1970-01-01
          • 2019-12-21
          • 2019-11-12
          • 2022-10-02
          相关资源
          最近更新 更多