将ajax请求绑定到特定元素Rails 3.1

我有一个用户列表,每个用户的名字旁边都有一个“关注”按钮。 ‘follow’请求通过ajax完成,然后按下按钮变为’unfollow’按钮。

我的代码在列出一个用户的情况下运行正常(并且还有列出多个用户的后端工作),但我想要的是列出多个用户,然后以某种方式将跟随请求绑定到特定元素’.follow_form’,每个按钮都是包含在中,因此只有单击的一个子“跟随”按钮变为“取消关注”。

我遇到问题的jquery代码如下:

/create.js.erb $(".follow_form").html("") 

  /destroy.js.erb $(".follow_form").html("") 

提交表单时,显然所有.follow_form元素都被更改但我无法弄清楚如何绑定正确的元素?

我尝试过的一些代码之一(对于create.js.erb)是:

  $("input.follow").bind( function() { $(this).closest(".follow_form").html("") }); 

但没有回应???

您可能应该在ajax:success执行此操作ajax:success回调,因为它自动绑定到对象。

您可以删除这些.js.erb文件,只需在控制器中呈现它们:

 def create # creation code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/unfollow' ) }, :status => :created end def destroy # deletion code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/follow' ) }, :status => :no_content end 

然后在你的javascript文件中:

 $('input.follow, input.unfollow').live('ajax:success', function(data, json, response) { $(this).closest(".follow_form").html(json.new_button); }); $('input.follow, input.unfollow').live('ajax:error', function(data, xhr, response) { // handle the ajax error here });