【问题标题】:Rails 3 ajax response is not executedRails 3 ajax响应未执行
【发布时间】:2011-07-28 18:55:56
【问题描述】:

我正在我的应用程序中创建一个简单的 ajax 功能,用户可以通过链接增加“喜欢计数”。

我已设法获取运行控制器代码的链接,并且浏览器正在收到响应,但响应未执行。

点赞链接不完整:

.likes                      
  .like_up                                                                  
    = link_to( image_tag('/images/thumb_up.png'), '/like/' + question.id.to_s, :remote => true)
  #like_count
    = 22# question.likecount                                                
  .like_down
    = link_to( image_tag('/images/thumb_down.png'), '/dislike/' + question.id.to_s, :remote => true)

它进入 likes_controller:

def up
  @like = current_user.likes.create( :question_id => params[:question_id], :like => true )
  respond_to do |format|
    format.js
  end
end

然后在我的 up.js.haml 中我只是有一个调试 javascript:

alert('2');

没有别的了。

当我在浏览器中按赞链接时,rails 日志告诉我它已经渲染了 js.haml

...
Rendered likes/up.js.haml within layouts/application (104.9ms)
Completed 200 OK in 923ms (Views: 116.3ms | ActiveRecord: 20.1ms)

当我查看浏览器得到的响应时,它看起来确实像 up.js.haml 呈现到我的应用程序布局中放置了 yield 标记的位置。

  <div class='content'>
    alert('2');
  </div>

我怀疑这不是浏览器想要返回的内容。此外,在 ajax 请求期间查看 firebug 控制台时,发送请求后没有任何反应。

有人能找出为什么这不起作用吗?我发现的每个教程和指南都以与我在这里相同的方式执行此操作。

【问题讨论】:

    标签: ruby-on-rails-3 jquery haml


    【解决方案1】:

    首先,确保内容类型正确:

    curl --head -X POST http://localhost:8080/....
    

    我认为Content-Type 应该是text/javascript

    其次,我认为您想禁用布局,以便DIV 不会出现在输出中。

    def up
      @like = current_user.likes.create( :question_id => params[:question_id], :like => true )
      respond_to do |format|
        format.js { render :partial => 'up', :layout => false }
      end
    end
    

    或者可以在整个控制器中禁用它

    layout false
    

    【讨论】:

    • 谢谢 :) 禁用布局解决了这个问题。 curl 说即使在 ajax 开始工作之后,Content-Type 也是 text/html。
    • 也许你可以渲染 :js => 'up' 或渲染 :partial => 'up', :format => 'json'
    • 这也是为我解决的问题,尽管我以前从未包含过它。知道为什么会这样吗?
    【解决方案2】:

    它以一种简单的远程形式发生在我身上。

    即使是开发环境,重启服务器后也可以工作。

    希望我能节省我浪费的时间。

    最好的问候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多