Ruby - Rails - Pass text to javascript

2020-04-16 04:07发布

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

2条回答
萌系小妹纸
2楼-- · 2020-04-16 04:29

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

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

So:

$('#error').text("<%= escape_javascript(@i[:error]) %>");
查看更多
够拽才男人
3楼-- · 2020-04-16 04:50

If you specify what debugger says it would be easier to understand the problem. This code for erb views works fine:

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

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

Pay attention that emptiness of string is checked by blank? method, I think it look much nicer than using != operator.

查看更多
登录 后发表回答