Ruby - Rails - 将文本传递给 javascript [英] Ruby - Rails - Pass text to 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]) %>");
这篇关于Ruby - Rails - 将文本传递给 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文