2

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

js.erb 文件 -

<% 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 %>
4

2 回答 2

2

是的,可能是因为换行。您可以使用escape_javascript.

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

所以:

$('#error').text("<%= escape_javascript(@i[:error]) %>");
于 2012-05-13T13:28:09.283 回答
0

如果您指定调试器所说的内容,则更容易理解问题。此 erb 视图的代码工作正常:

<% @i = {} %>
<% @i[:error] = "Error" %>  

<% unless @i[:error].blank? %>
  <script>
    $(document).ready(function() {
      $('#error').text('<%= @i[:error] %>'); // Works fine
    });
  </script>
<% end %>

注意字符串的空性是用空格检查的吗?方法,我认为它看起来比使用!=运算符要好得多。

于 2012-05-13T12:44:56.607 回答