2011-09-03 65 views
1

我有一个张贴'想法'的表单。我已经设置使用ajax来做到这一点。 它基本上只是将发布思想的想法和用户附加到想法列表的末尾。在create.js.erblink_to从javascript中调用JavaScript时打破JavaScript?

$('#thoughts') 
    .append("<div class='thoughts'><%= @thought.user.name %><p><%= @thought %></p></div>"); 

使用这个JavaScript 这worksas预期,但是当我尝试添加一个链接到谁张贴的思想,像这样

$('#thoughts') 
    .append("<div class='thoughts'><%= link_to(@thought.user.name, @thought.user) %><p><%= @thought %></p></div>"); 

用户它不追加思想想法的列表。它仍将其发布到数据库,但不显示它。

任何帮助将不胜感激,谢谢。

回答

3

你必须使用escape_javascript这样的:

$('#thoughts') 
    .append("<div class='thoughts'><%= escape_javascript(link_to(@thought.user.name, @thought.user)) %><p><%= @thought %></p></div>"); 

如果你不使用escape_javascript create.js.erb会生成以下代码,不显而易见的原因工作:

$('#thoughts') 
    .append("<div class='thoughts'><a href="/thoughts/1">Username</a><p>Thought</p></div>"); 
             #^
             # This is the problem, 
             # which is fixed by escape_javascript