Ruby - Rails - Pass text to javascript

后端 未结 2 1105
野的像风
野的像风 2021-01-21 18:23

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 -

&l         


        
相关标签:
2条回答
  • 2021-01-21 19:05

    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]) %>");
    
    0 讨论(0)
  • 2021-01-21 19:07

    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.

    0 讨论(0)
提交回复
热议问题