简体   繁体   中英

Rails - ajax page partial update

I have my home.html.haml page rendering 3 partials:

%h1 Foo
#foo1
 = render partial: 'foo/foo', locals: {items: @foo1_items}
#foo2
 = render partial: 'foo/foo', locals: {items: @foo2_items}
#foo3
 = render partial: 'foo/foo', locals: {items: @foo3_items}

Currently, I have some remote links that refresh these parts individually firing an ajax call to to the home page:

= link_to 'refresh', home_path(mode: 'foo1'), remote:true
= link_to 'refresh', home_path(mode: 'foo2'), remote:true
= link_to 'refresh', home_path(mode: 'foo3'), remote:true

and I have a home.js.erb that contains something like this:

<% if params[:mode] == 'foo1'%>
$('#foo1').html('<%= j(render partial: 'foo/foo', locals: {items: @foo1_items}) %>')
<% elsif params[:mode] == 'foo2'%>
$('#foo2').html('<%= j(render partial: 'foo/foo', locals: {items: @foo2_items}) %>')
<% else %>
$('#foo3').html('<%= j(render partial: 'foo/foo', locals: {items: @foo3_items}) %>')
<% end %>

I am wondering:

  1. if this is the default(suggested, best) Rails way to do a partial page refresh or generally the way to handle ajax requests?
  2. if it would be faster to have server respond with pure html and let the client (javascript) to do the replacing?
  3. how do you handle this in your application?
  1. Yes, it is the right way to do it in Rails
  2. It will be the same thing as far as processing is concerned. Whatever is spitted out of server is executed on client browser and elements get updated. With server side you have more control with ERB.
  3. The same way you have done it.

Hope this will help

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