Rails 3,处理ajax响应

Using Ruby on Rails 3, I have a page with a list of comments and I want to show a form using ajax whenever the user presses a comment's reply button.

So far, I have a partial called _form_comment.html.erb with the html for the form. There's no problem with this.

In the view, this is the code for the reply buttons:

link_to "Reply", {:controller => "catalog", :action => "form_comment", :id => c.id}, :remote => true, :class => "btn_reply_comment"

In the controller, I've added this action, that returns the partial whenever a reply button is pressed:

def form_comment
    if request.xhr?
        render:partial => "form_comment"
    end
end

And, in order to "do something" with the response, I have this script

$(document).ready(function(){
    $(".btn_reply_comment")
        .bind("ajax:success", 
              function() { alert("Ajax response"); });
});

When I press the reply button, I can check, using Firebug, that the ajax request is returning a 304 not modified code. I've read some other threads saying that I should disable the cache in the ajax request, but given I'm not manually using $.ajax..., I don't know how to modify that.

What can I do?

I think you have to bind to the "ajax:success" event on the form created by the link_to helper, and not on the "a" link element.

so try to bind to:

".btn_reply_comment form"

Anyway I suggest using a normal link_to or "a" element, and some jquery code to make the ajax request and handle the callback like:

$(".btn_reply_comment").on("click", function(){
   $.get($(this).attr("href"), function(data){
     eval(data)
   })
})

ps: "on" requires jquery >= 1.7, if you don't have it use "bind"