我很难在按下按钮时尝试刷新部分内容。我想简单地刷新div,而不是整个页面。以下是我在视图中的内容:
<div id="ajax">
<%= render 'layouts/confessions' %>
</div>
然后在我的部分_confessions.html.erb
中,我有一些基本的html和两个类似的按钮:
<%= form_tag( { :controller => :confessions, :action => :upvote, :id => conf.id }, { :method => :put } ) do %>
<%= submit_tag 'Like' %>
<% end %>
我的confessions_controller.rb:
def upvote
@confession = Confession.find(params[:id])
Confession.increment_counter :upvotes, @confession
respond_to do |format|
format.js
end
end
最后,upvote.js.erb
:
$('#ajax').html("<%= escape_javascript(render(:partial => 'confessions')).html_safe %>");
提交到我的数据库的操作正在运行,但页面现在重定向到/upvote?id=9
(id可能不同),而不是仅刷新div。我究竟做错了什么?我是Rails的新手,所以我可能会遗漏一些完全明显的东西......
编辑:这是我的文件夹结构:
我的观点:views/pages/home.html.erb
我的部分:views/layouts/_confessions.html.erb
我的控制器:controllers/confessions_controller.rb
我的js.erb文件:views/confessions/upvote.js.erb
rake routes
之后
confessions GET /confessions(.:format) confessions#index
POST /confessions(.:format) confessions#create
new_confession GET /confessions/new(.:format) confessions#new
edit_confession GET /confessions/:id/edit(.:format) confessions#edit
confession GET /confessions/:id(.:format) confessions#show
PUT /confessions/:id(.:format) confessions#update
DELETE /confessions/:id(.:format) confessions#destroy
upvote /upvote(.:format) confessions#upvote
downvote /downvote(.:format) confessions#downvote
root / pages#home
答案 0 :(得分:4)
确保在application.js
中有此功能//= require jquery
//= require jquery_ujs
仅供参考:Rails form_for :remote=>true is not calling js method
然后,改变这个,
$('#ajax').html("<%= escape_javascript(render(:partial => 'confessions')).html_safe %>");
致:
$('#ajax').html("<%= escape_javascript(render(:partial => 'layouts/confessions')).html_safe %>");
答案 1 :(得分:1)
添加:remote =&gt;真
<%= form_tag( { :controller => :confessions, :action => :upvote, :id => conf.id }, { :method => :put, :remote=>true } ) do %>
另外 - 阅读轨道路线,了解如何设置PUT口供/ upvote路线。
http://guides.rubyonrails.org/routing.html#adding-more-restful-actions