意想不到的令牌&为''

时间:2014-03-19 10:11:28

标签: javascript ruby-on-rails ruby arrays

我已将currency_symbol_list定义为

  def currency_symbol_list
    result = []

    Currency.active.each do |currency|
      pre = currency.prefix? ? currency.symbol : ""
      post = currency.prefix? ? "" : currency.symbol

      result << "[#{currency.id}, '#{pre}','#{post}']"
    end

    result.join(', ')
  end

这将得到结果

"[1, '$',''], [2, '','pts'], [3, '&pound;',''], [4, '&euro;',''], [5, 'Rs. ',''], [6, 'CHF ',''], [7, 'C$','']"

到此为止我没有任何问题。我按照自己的意愿获得了价值,但是当我用javascript

调用currency_symbol_list方法时
 <script type="text/javascript">
    var currency_list = [<%= currency_symbol_list %>];
    var accounts_to_currency_list = [<%= accounts_to_currency_symbol_list(@child.pending_accounts) %>];
</script>

我收到Uncaught SyntaxError: Unexpected token &错误。并显示不同的数据

 <script type="text/javascript">
    var currency_list = [[1, &#39;$&#39;,&#39;&#39;], [2, &#39;&#39;,&#39;pts&#39;], [3, &#39;&amp;pound;&#39;,&#39;&#39;], [4, &#39;&amp;euro;&#39;,&#39;&#39;], [5, &#39;Rs. &#39;,&#39;&#39;], [6, &#39;CHF &#39;,&#39;&#39;], [7, &#39;C$&#39;,&#39;&#39;]];
    var accounts_to_currency_list = [[25061, &#39;$&#39;,&#39;&#39;, 1], [25062, &#39;&#39;,&#39;pts&#39;, 2]];
</script>

在预变量之前和之后添加变量&#39;之后。由于我收到Uncaught SyntaxError: Unexpected token &错误。如何解决?

1 个答案:

答案 0 :(得分:1)

使用'&lt;%= ...%&gt;'时,Rails会添加&#39&amp;因为它逃脱了HTML特殊字符。您可以使用rawhtml_safe

停用此行为
var currency_list = [<%= raw currency_symbol_list %>];
var accounts_to_currency_list = [<%= raw accounts_to_currency_symbol_list(@child.pending_accounts) %>];

您可以在此处获得完整的说明:http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/