Javascript js:未定义的局部变量或方法'current#u user';
我使用嵌入ruby代码的js文件:Javascript js:未定义的局部变量或方法'current#u user';,javascript,ruby-on-rails,angularjs,ruby-on-rails-4,Javascript,Ruby On Rails,Angularjs,Ruby On Rails 4,我使用嵌入ruby代码的js文件: function MyController($scope) { $scope.sayHello = function() { var hello = <%= current_user.name %>; $scope.greeting = hello; }; } 函数MyController($scope){ $scope.sayHello=函数(){ var hello=; $scope.greeting=hello; }
function MyController($scope) {
$scope.sayHello = function() {
var hello = <%= current_user.name %>;
$scope.greeting = hello;
};
}
函数MyController($scope){
$scope.sayHello=函数(){
var hello=;
$scope.greeting=hello;
};
}
但是我发现了一个错误未定义的局部变量或方法current\u user
,它指向
=javascript\u包括标签“应用程序”、“数据涡轮链接跟踪”=>true
我怎样才能修好它?谢谢 使用最简单的方法将数据从rails环境传递到javascript环境(换句话说:从服务器传递到客户端)
在控制器中
# 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页面)
使用最简单的方法将数据从rails环境传递到javascript环境(换句话说:从服务器传递到客户端)
在控制器中
# 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页面)
JS
要扩展Benjamin Sinclaire的答案,您必须记住Rails是一个后端系统;JS是前端
这意味着所有Rails变量仅在后端的Rails文件中可用-您的浏览器接收的是一组预先呈现的HTML
文件,其中填充了您的数据
问题是,如果不将数据从Rails转换为“JS”,JS就无法读取Rails
数据。JS看到的只是页面上的HTML元素
--
数据
为了在JS/前端
中共享变量,例如当前用户
,基本上需要将其传递到HTML层
您可以通过设置隐藏元素(并设置其属性)或在布局中设置变量来完成此操作
如前所述,最有效的方法是使用gem,这是本杰明·辛克莱尔(Benjamin Sinclaire)所讨论的
要扩展Benjamin Sinclaire的答案,您必须记住Rails是一个后端系统;JS是前端
这意味着所有Rails变量仅在后端的Rails文件中可用-您的浏览器接收的是一组预先呈现的HTML
文件,其中填充了您的数据
问题是,如果不将数据从Rails转换为“JS”,JS就无法读取Rails
数据。JS看到的只是页面上的HTML元素
--
数据
为了在JS/前端
中共享变量,例如当前用户
,基本上需要将其传递到HTML层
您可以通过设置隐藏元素(并设置其属性)或在布局中设置变量来完成此操作
如前所述,最有效的方法是使用gem,Benjamin Sinclaire
已经讨论过它您是否尝试从资产文件中访问变量?这是行不通的,因为这些文件是静态编译的,而不是针对每个文件动态编译的request@PeterSorowka看来你是对的。您能告诉我,我应该在视图目录中尝试吗?您应该尝试构造代码,使您的资产不依赖于请求运行时变量。例如,您可以将用户名作为参数传递给sayHello
。然后,您仍然可以在资产中定义函数,但在模板中调用为内联JavaScript您是否尝试从资产文件中访问该变量?这是行不通的,因为这些文件是静态编译的,而不是针对每个文件动态编译的request@PeterSorowka看来你是对的。您能告诉我,我应该在视图目录中尝试吗?您应该尝试构造代码,使您的资产不依赖于请求运行时变量。例如,您可以将用户名作为参数传递给sayHello
。然后,您仍然可以在资产中定义函数,但在模板中调用为内联JavaScript
var hello = gon.current_user_name;