简体   繁体   English

Rails视图中的AJAX 404错误

[英]AJAX 404 Error in Rails View

I'm trying to load the comment for each article on my index page using AJAX. 我正在尝试使用AJAX在index页面上为每篇文章加载评论。

What am I missing here? 我在这里想念什么?

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 %>"}

Controller: 控制器:

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

JS: 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);

Show: 节目:

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

EDIT: 编辑:

So the console log displays the following link but I guess the correct URL would be localhost:3000/articles/1/comment/1 因此,控制台日志显示以下链接,但我猜正确的URL为localhost:3000/articles/1/comment/1

How do I fix it? 我如何解决它?

Console log: 控制台日志:

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

routes.rb routes.rb

resources :articles do
  resources :comments do
  end
end

If you change your loadComment function to this, it should work -- 如果您将loadComment函数更改为此,它将正常工作-

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!");
      }
    });
  });
};

The route for the 'show' action is /comments/:comment_id “显示”操作的路线为/comments/:comment_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM