简体   繁体   中英

Ajax to refresh partial not working in rails

I want to show the user articles info in homepage, user click the My Articles link, then will show the info, doesn't need to refresh whole page:

for ArticlesController :

  def index
    @user = User.find(params[:user_id])
    @articles = @user.articles.page params[:page]
    respond_to do |format|
      format.html { render :index }
      format.js
    end
  end

index.html.erb :

<%= render 'index/my_articles' %>

partial view _my_articles.html.erb :

<div class="panel panel-default" id="my_articles">
  <ul class="list-group">
    <% @user.articles.each do |article| %>
    <li class="list-group-item">
        <%= link_to article.title, user_article_path(@user, article) %>
      <% end %>
    </li>
  </ul>
</div>

index.js.erb :

 $("#my_articles").html("<%= escape_javascript(render 'index/my_articles').html_safe %>");

nothing shows when I click the link, but the partial rendered according to rails log:

Started GET "/users/55daf9df57d2fa0a9c000006/articles" for ::1 at 2015-08-30 00:22:20 +0800
Processing by ArticlesController#index as JS
  Parameters: {"user_id"=>"55daf9df57d2fa0a9c000006"}
  Rendered index/_my_articles.html.erb (3.7ms)
  Rendered articles/index.js.erb (6.4ms)
Completed 200 OK in 24ms (Views: 21.7ms | ActiveRecord: 0.0ms)

I am not familiar with ajax and JS, hope someone can help me, Thanks in advance!

Try this way. Add :remote=> true and put the end tag after the li tag.

<div class="panel panel-default" id="my_articles">
 <ul class="list-group">
  <% @user.articles.each do |article| %>
  <li class="list-group-item">
    <%= link_to article.title, user_article_path(@user, article), :remote => true %>
</li>
<% end %>
</ul>
</div>

In the index.js.erb edit to

$("#my_articles").html("<%= escape_javascript(render 'my_articles').html_safe %>");

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