简体   繁体   中英

AJAX 404 Error in Rails View

I'm trying to load the comment for each article on my index page using AJAX.

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:

#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

How do I fix it?

Console log:

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

routes.rb

resources :articles do
  resources :comments do
  end
end

If you change your loadComment function to this, it should work --

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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