Ajax刷新部分不在rails中工作

时间:2015-08-29 16:40:29

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4

我想在首页显示用户文章信息,用户点击My Articles链接,然后会显示信息,不需要刷新整个页面:

代表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' %>

部分视图_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 %>");
单击链接时没有显示任何内容,但部分根据rails日志呈现:

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)

我不熟悉ajax和JS,希望有人可以帮助我,提前致谢!

1 个答案:

答案 0 :(得分:0)

试试这种方式。添加:remote =&gt;如果是,请将结束标记放在li标记之后。

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

在index.js.erb中编辑

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