RAILS Auto refresh partial

旧城冷巷雨未停 提交于 2019-12-11 06:58:46

问题


I have a controller events with action show :

  def show
    @event = Event.get(params[:id])

    if !connected? || !@event 
      return redirect_to request.referrer || root_path
    end

    @requests = @event.get_requests
  end

In view show.html.erb i have

<script>
  $(document).ready(
     function() {
      setInterval(function() {
        $('#requests').load('/events/reload_requests');
    }, 2000);
  });
</script>
...
<div class="party-block" id="requests">
    <%= render partial: 'requests' %>
</div>
...

The javascript function call controller method events/reload_requests :

def reload_requests
  @requests = @event.get_requests
  render partial: 'events/requests'
end

And content of partial _requests.html.erb :

<%= Time.now %>
<h4><%= t '.requests' %></h4>
<% @requests.each do |r| %>
 <span class="request">
 ...
<% end %>

Problem : The javascript function load all the content of my show.html.erb page in div #requests, but in the copy of show.html.erb in the div, it refresh div #request correctly : enter image description here You can see, in show#requests i have the content of show. Than you


回答1:


After re-reading your question, I think I understood your problem.

When you call the #load method, the HTML returned is actually your whole show.html.erb template.. which gets inserted into your $('#requests') element. Is that correct?

In the jQuery docs, you can find the following at: http://api.jquery.com/load/

Loading Page Fragments

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. (...)

$( "#result" ).load( "ajax/test.html #fragment" );

Maybe if you modify your script tag as follow:

<script>
  ...
        $('#requests').load('/events/reload_requests #requests');
  ...
</script>

you can insert only the fragment of the HTML you are interested in.

Please let me know if that was not your question.

Also, if your request to 'event/reload_requests' is returning your show.html.erb template, you may be mistakenly routing the event/reload_requests endpoint to your #show action.

Edit#1

The cleanest way to fix the nested div problem seems to be to add a container div and load from there:

$('#requestsContainer').load('/events/reload_requests #requests');

html:

<div id="requestsContainer">
  <div class="party-block" id="requests">
      <%= render partial: 'requests' %>
  </div>
</div>


来源:https://stackoverflow.com/questions/39425847/rails-auto-refresh-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!