问题
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