Rails视图中的AJAX 404错误

时间:2016-03-12 12:04:34

标签: ruby-on-rails ajax view

我正在尝试使用AJAX在index页面上加载每篇文章的评论。

我在这里缺少什么?

指数:

 #welcome/index.haml
    - @articles.each do |article|
       = article.title
       - article.comments.each do |comment|
         %comment-content{ :id => "comment-<%= comment.id %>", :class => "comment-block", "data-comment-id" => "<%= comment.id %>"}

控制器:

#comments_controller.rb
class CommentsController < ApplicationController
  def show
    respond_to do |format|
        format.js { }
    end
  end
end

JS:

#comments.js
var loadComment;

loadComment = function() {
  return $('.comment-block').each(function() {
    var $comment_block;
    $comment_block = $(this);
    return $.ajax('/comments/show', {
      type: 'GET',
      dataType: 'script',
      data: {
        comment_id: $comment_block.data('comment-id')
      },
      error: function(jqXHR, textStatus, errorThrown) {
        return console.log("AJAX Error: " + textStatus);
      },
      success: function(data, textStatus, jqXHR) {
        return console.log("Worked OK!");
      }
    });
  });
};

$(document).ready(loadComment);

$(document).on('page:change', loadComment);

显示:

 #comments/show.js.erb
 $('#comment-<%= @comment.id %>').append('j render(@comment.content)');

编辑:

因此,控制台日志显示以下链接,但我想正确的URL将是localhost:3000/articles/1/comment/1

我该如何解决?

控制台日志:

http://localhost:3000/show?comment_id=%3C%25%3D+comment.id+%25%3E&_=1457784667124

的routes.rb

resources :articles do
  resources :comments do
  end
end

1 个答案:

答案 0 :(得分:2)

如果你将loadComment函数改为this,它应该可以工作 -

loadComment = function() {
  return $('.comment-block').each(function() {
    var $comment_block;
    $comment_block = $(this);
    comment_id: $comment_block.data('comment-id')
    return $.ajax('/comments/'+comment_id+, {
      type: 'GET',
      dataType: 'script',
      error: function(jqXHR, textStatus, errorThrown) {
        return console.log("AJAX Error: " + textStatus);
      },
      success: function(data, textStatus, jqXHR) {
        return console.log("Worked OK!");
      }
    });
  });
};

“show”操作的路线为/comments/:comment_id