weixin_33724059 2012-01-14 01:35 采纳率: 0%
浏览 14

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?

  • 写回答

1条回答 默认 最新

  • weixin_33716154 2012-01-14 03:03
    关注

    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"

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题