Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - How do I render partial via ajax in rails3 and jQuery

I could do sth like this in rails 2:

def show_rec_horses
  rec_horses = Horses.find(:all)
  page["allHorses"].replace_html :partial => "horses/recommended", :locals => 
 {:rec_horses => rec_horses}
end

How do I do this in Rails3 with jQuery. So how can I replace html of my div with a partial via ajax call(link_to :remote => true) in Rails3.

I tried sth like (in my show_rec_horses.js.erb):

$("#interactionContainer").update("<%= escape_javascript(render("horses/recommended"))%>");

And nothing happens. I tried some other variations but none worked. What am doing wrong? Should this be approached in some other way? Any answer would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, let's start with the controller.

def show_rec_horses
  @rec_horses = Horses.find(:all)

  respond_to do |format|
    format.html # show_rec_horses.html.erb
    format.js   # show_rec_horses.js.erb
  end
end

This will make sure the correct templates are being rendered for either a html request or a javascript request. If you just need to respond to a javascript request, delete the html part.

Now let's say you have a page containing the following:

<p><%= link_to 'Show Horses', show_rec_horses_path, remote: true %></p>

<div id="interactionContainer"></div>

Clicking the link will make a request to the show_rec_horses action in your controller, this action will render the javascript file show_rec_horses.js.erb.

This javascript file should contain something like this:

$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')

Now your container will be filled with the content of horses/_reccommended.html.erb, which for example could contain:

<% rec_horses.all.each do |rec_horse| %>
  <p><%= rec_horse.name %></p>
<% end %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...