【问题标题】:interpolating ruby in JavaScript unexpected token error在 JavaScript 中插入 ruby​​ 意外令牌错误
【发布时间】:2013-09-04 19:50:38
【问题描述】:

我有一个使用 Ember、CoffeeScript、Haml 和 Rails 的应用程序的源代码。在布局文件中,它使用这段代码启动应用程序,其中有一个用 Ruby 编写的 current_user_json 辅助方法

:javascript
    App.ready = function() {
      App.initApp(jQuery.parseJSON('#{current_user_json}'))
    }

尝试使用 erb 和 JavaScript 重新创建应用程序,我收到意外的令牌错误

Uncaught SyntaxError: Unexpected token # 

如果我执行以下操作

  <script type="text/javascript">
 App.ready = function() {
      App.initApp(jQuery.parseJSON('#{ current_user_json}'));
    }
  </script>

为什么该令牌是意外的,我该如何避免该错误?

【问题讨论】:

  • #{ variable } 插值仅适用于 HAML。

标签: javascript ruby haml


【解决方案1】:

根据您的问题,我无法判断它在 HAML 中是否不适合您。我会假设是这样,因为我也使用相同的方法并且效果很好。

至于ERB,我个人不使用它,但我认为你不能像那样直接放入一个字符串,试试这个:

<script type="text/javascript">
  App.ready = function() {
    App.initApp(jQuery.parseJSON('<%= current_user_json %>'));
  }
</script>

【讨论】:

    【解决方案2】:

    把它改成双引号。

    App.initApp(jQuery.parseJSON("#{ current_user_json}"));

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 2011-07-05
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      相关资源
      最近更新 更多