[英]Correct way to use Ajax with rails
I am trying to add ajax to a voting system but having difficulty targeting individual elements with jQuery. 我正在尝试将ajax添加到投票系统,但是很难用jQuery定位单个元素。 This is what i have so far: 这是我到目前为止所拥有的:
Vote Link in index action 在索引操作中投票链接
<%= link_to post_votes_path(post), :method => 'post', :remote => true do %>
<span class="score"><%= post.votes.size %></span>
<% end %>
Create action in Vote controller 在投票控制器中创建动作
def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create
respond_to do |format|
format.html { redirect_to root_url }
format.js
end
end
jQuery in votes#create view (create.js.erb) jQuery在表决#创建视图(create.js.erb)
$('.score').html("I voted");
Trouble is when i click the link to vote it changes the html for all posts not just the post i tried voting on. 麻烦的是,当我单击链接进行投票时,它更改了所有帖子的html,而不仅仅是我尝试投票的帖子。 Dont have much experience with jQuery so i cant help but think i am missing something obvious. 没有jQuery的丰富经验,所以我禁不住想我缺少明显的东西。 Any ideas ? 有任何想法吗 ?
all your spans have the .score class. 您所有的跨度都有.score类。 that's the reason for all be changed. 这就是所有改变的原因。
This is a possible solution. 这是一个可能的解决方案。 Change in your html: 更改您的html:
<span class="score p_<%= post.id%>"><%= post.votes.size %></span>
And then change in your create.js.erb 然后更改您的create.js.erb
$('.score.p_<%= @post.id %>').html("I voted");
I typically just use JQuery's $.post. 我通常只使用JQuery的$ .post。 I am using asp.net, but assume rails will work with that as well. 我正在使用asp.net,但假设rails也可以使用。
$.post("/someurltoyouraction", {myval:val},function(data){
// do stuff after post
});
This will produce an Ajax post request. 这将产生一个Ajax发布请求。 You can define your post parameters in the {myval:val}
object to match your requirements. 您可以在{myval:val}
对象中定义发布参数,以符合您的要求。 It's essentially a key value definition based object {key:value}
本质上是基于键值定义的对象{key:value}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.