Ruby - Rails - 将文本传递给 javascript

Ruby - Rails - 将文本传递给 javascript

问题描述:

为什么这不将文本传递给 javascript/jquery.?@i[:error] 里面肯定有一个字符串,我可以在控制台上打印出来.

Why isn't this passing text to javascript/jquery.? @i[:error] definitely has a string in it, I can print that on console.

js.erb 文件 -

js.erb file -

<% if @i[:error] != "" %>
<% puts "--> " + @i[:error]  %>
#--> error
#Validation error(s):
#-  Item Is not defined or blank. # that's the error string in @i[:error]

$(function() {
$("#error_message").attr("class", "message_error");
$('#error').text("<%= @i[:error]%>"); #Not working for @i[:error]
#$('#error').text("<%= "#{@i[:error]}"%>");#Not working for @i[:error]

#$('#error').text("Test"); #This is working
#$('#error').text("<%= "?????"%>"); #This is working
});
<% else %>
........#fine here
<% end %>

是的,可能是换行的原因.您可以使用 escape_javascript修复它>.

Yes, it's probably because of the line break. You can fix it by using escape_javascript.

为 JavaScript 转义回车符和单引号和双引号段.

Escapes carriage returns and single and double quotes for JavaScript segments.

所以:

$('#error').text("<%= escape_javascript(@i[:error]) %>");