简体   繁体   English

如何在Ruby on Rails中使用Ajax加载部分

[英]How to load a partial using Ajax in Ruby on Rails

I have a partial to load when a search is detected. 当检测到搜索时,我有部分要加载。 It may take a very long time to load in some cases, so I would like it to load via Ajax once the page is fully loaded otherwise it will most likely cause a timeout. 在某些情况下,加载可能需要很长时间,因此,我希望在页面完全加载后通过Ajax加载,否则很可能会导致超时。

The way I am doing it currently is resulting in a synchronously load. 我目前的操作方式导致同步加载。

I would also like a loading screen to be shown, until it's fully loaded. 我还希望显示一个加载屏幕,直到完全加载为止。 This is working currently but only with the timeout set, as its a synchronous load. 目前,这是有效的,但仅在设置了超时的情况下作为同步负载。

    <% if(params[:q][:name_cont].present?) %>

  <script>
    $( document ).ready(function() {

      function load_partial() {     
        $("div.super_search").replaceWith('<%= escape_javascript(render partial: 'super_search_tp') %>');
                                          }

                                          // use setTimeout() to execute
                                          setTimeout(load_partial, 1000)

      });

  </script>

  <div class="super_search">

    <i class='fa fa-spinner fa-spin'></i> Loading Product Analysis...

  </div>

<% end %>

Create a method for the partial in the controller: 为控制器中的局部对象创建一个方法:

  def super_search
    @search = @@products
    render :layout => false
  end

Rename the partial so it was the view for this method. 重命名partial,因此它是此方法的视图。

Add in the @@products to the index method so that the data from the search can be used in the new method: @@products添加到index方法中,以便可以将搜索中的数据用于新方法中:

@@top_products = @q.result

Code to render the partial: 渲染部分代码:

<% if(params[:q][:name_cont].present?) %>

      <script>

        $.ajax({
          url: "/products/super_search",
          cache: false,
          success: function(html){
            $("#foo-bar").replaceWith(html);
          }
        });

      </script>

      <div class="super_search" id="foo-bar">

        <i class='fa fa-spinner fa-spin'></i> Loading Product Analysis...

      </div>

        <% end %>

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

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