AJAX渲染400错误

时间:2016-03-13 18:20:59

标签: ruby-on-rails ajax

目标是使用AJAX在我的index页面上加载每篇文章的评论。

我收到bad request错误400:

ERROR bad URI `/comments/%3C%=%20comment.id%20%%3E?_=1457892605480'.

指数:

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

JS:

    #comments.js
    var loadComment = function() {
    return $('.comment-content').each(function() {
    var comment_id = $(this).data('comment-id');
    return $.ajax({
      url: /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!");
      }
    });
  });
};

$(document).ready(loadComment);

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

显示:

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

路线:

resources :articles do
      resources :comments do
      end
end

2 个答案:

答案 0 :(得分:1)

您的网址必须是字符串:

url: "/comments/" + comment_id

答案 1 :(得分:1)

当您对错误消息中的URL进行URL编码时,您将获得以下内容:

ERROR bad URI `/comments/<%= comment.id %>?_=1457892605480'.

看到这一点,错误变得非常明显:HAML模板中的插值是错误的。您需要使用ruby字符串插值样式,而不是ERB插值样式,如HAML docs中所述:

%comment-content{ :id => "comment-#{comment.id}", :class => "comment-content", "data-comment-id" => comment.id }