2016-03-13 169 views
0

目標是使用AJAX爲我的index頁面上的每篇文章加載評論。AJAX渲染400錯誤

我得到一個錯誤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 
+0

您的網址必須是一個字符串:URL:「/評論/」 + COMMENT_ID – toddmetheny

回答

1

當你URLdecode錯誤消息的URL,你會得到如下:

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

看到這一點,錯誤變得非常清楚:HAML模板中的插值是錯誤的。而不是ERB插值風格,您需要用紅寶石串插風格,如HAML docs描述:

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

感謝。現在,我得到一個路由錯誤'ActionController :: RoutingError(沒有路由匹配[GET]「/ comments/2」):'。正確的路線是'articles/1/comments/2',我不知道如何解決,但我想這是一個不同的問題。 – Liroy

1

您的網址必須是一個字符串:

url: "/comments/" + comment_id