问题
I am having trouble re-rendering a partial through an Ajax request. I can currently pass other things through the js file such as alert() and even changing the html in the current div. But when I try and render the partial (rating, in this instance), nothing will refresh. The partials work fine in the sense that they render on pagination and on load, but not after I click an upvote or downvote. I'm using nested partials so that it renders _tracks first, then _rating. Here's what I have..what am I missing?
vote.js.erb
$(".rating").html("<%= escape_javascript(render(:partial => 'rating')) %>")
With this I also these, with no success.
$(".rating").html("<%= escape_javascript(render("rating")) %>")
$(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => track }) ) %>")
This, on the other hand, does work:
$(".rating").html("<%= escape_javascript("test text here) %>")
_tracks.html.erb
<% for track in @tracks %>
<div class="span4">
<div class="track">
<div class="rating">
<%= render :partial => "rating", :locals => { :track => track } %>
</div>
<a href="<%= track.youtube_link %>"></a>
<% if current_user.admin? %>
<%= link_to "delete", track, method: :delete, confirm: "You sure?" %>
<%= link_to "edit", edit_track_path(track) %>
<% end %>
</div>
</div>
<% end %>
_rating.html.erb
<% vt = track.votetype(current_user) %>
<% if vt != "up" %>
<%= link_to image_tag("up_arrow.png", alt: "Upvote"), vote_path(track, :type => "up"), :remote => true %>
<% elsif %>
<%= "up" %>
<% end %>
<%= track.rating %>
<% if vt != "down" %>
<%= link_to image_tag("down_arrow.png", alt: "Downvote"), vote_path(track, :type => "down"), :remote => true %>
<% elsif %>
<%= "down" %>
<% end %>
track controller
@vote.update_attributes(:vote_type => params[:type])
if @vote.save
respond_to do |format|
format.html {redirect_to :back}
format.js
end
回答1:
$(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => track }) ) %>")
needs to be
$(".rating").html("<%= escape_javascript( render( :partial => "rating", :locals => { :track => @track }) ) %>")
The @ symbol passes the variable through, unlike the for loop in the previous partial where you didn't need it. Working fine now.
来源:https://stackoverflow.com/questions/11654021/rails-ajax-render-partial-voting-system