简体   繁体   中英

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.

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.

Add in the @@products to the index method so that the data from the search can be used in the new method:

@@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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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