[英]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: 我想在首页中显示用户文章信息,用户单击“ My Articles
链接,然后将显示该信息,不需要刷新整个页面:
for ArticlesController
: 对于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
: index.html.erb
:
<%= render 'index/my_articles' %>
partial view _my_articles.html.erb
: 部分视图_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
: 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: 单击链接后没有任何显示,但是根据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)
I am not familiar with ajax and JS, hope someone can help me, Thanks in advance! 我对ajax和JS不熟悉,希望有人可以帮助我,谢谢!
Try this way. 尝试这种方式。 Add :remote=> true and put the end tag after the li tag. 添加:remote => true并将结束标记放在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>
In the index.js.erb edit to 在index.js.erb中,编辑为
$("#my_articles").html("<%= escape_javascript(render 'my_articles').html_safe %>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.