link_to breaking javascript when calling from javascript in rails?
I have a form that posts a 'thought'. I have it set up to do this using ajax. It basically just appends the thought and the user who posted the thought to the end of the list of thoughts. This worksas expected using this javascript in create.js.erb
$('#thoughts')
.append("<div class='thoughts'><%= @thought.开发者_JAVA技巧user.name %><p><%= @thought %></p></div>");
but when i try to add a link to the user who posted the thought like so
$('#thoughts')
.append("<div class='thoughts'><%= link_to(@thought.user.name, @thought.user) %><p><%= @thought %></p></div>");
it does append the thought to the list of thoughts. It still posts it to the database but it doesn't display it.
Any help will be much appreciated, thank you.
You have to use escape_javascript
like this:
$('#thoughts')
.append("<div class='thoughts'><%= escape_javascript(link_to(@thought.user.name, @thought.user)) %><p><%= @thought %></p></div>");
If you don't use escape_javascript
create.js.erb will generate the following code, which does not work for obvious reasons:
$('#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
精彩评论