我有嵌入 ruby 代码的 js 文件:
function MyController($scope) {
$scope.sayHello = function() {
var hello = <%= current_user.name %>;
$scope.greeting = hello;
};
}
但是我发现了一个错误未定义的局部变量或方法current_user
,它指向
= javascript_include_tag "application", "data-turbolinks-track"=> true
我该如何解决这个问题?谢谢!
最佳答案
使用gon gem https://github.com/gazay/gon将数据从 Rails 环境传递到 javascript 环境(换句话说:从服务器到客户端)的最简单方法。
在你的 Controller 中
# Make sure first that current_user is not nil
gon.current_user_name = current_user.name
# As you can see we don't pass the whole `current_user` but only the data we need
# gon and javascript won't know how to use your Rails objects
# so pass only strings, integers, arrays and hashs
# (but you'll figure out all of this by your self, it's pretty natural)
在您的布局中(有关 gon 安装的更多信息可以在 gon github 页面中找到)
<head>
<%= include_gon %>
...
在你的 JavaScript 中
var hello = gon.current_user_name;
关于javascript - js : undefined local variable or method `current_user' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24500077/