我希望从 application.js 访问 current_user 变量(我将 application.js 重命名为 application.js.erb,以便服务器可以理解我的 ruby 代码),所以我得到了类似的内容:
function hello(){ alert("<%= current_user.name %>"); }
但它失败了:
我如何从位于 /assets/my_script.js.erb 的脚本中获取像 current_user 这样的会话变量,我认为它不应该能够,因为这些变量可能无法从公共站点访问,或者应该做什么这?
Thanks!
Application.js 不会在任何会话变量或方法的上下文中进行评估。从 javascript 访问用户名的最简单方法是在应用程序控制器的 before_action 中设置 cookie:
class ApplicationController < ActionController::Base
before_action :set_user
private
def set_user
cookies[:username] = current_user.name || 'guest'
end
end
然后,您可以从 app/assets 中的任何 js 访问 cookie:
alert(document.cookie);
一种更详细但可以说更干净的方法是创建一个访问当前用户并返回用户名的路由,例如
路线.rb
get 'current_user' => "users#current_user"
用户控制器.rb
def current_user
render json: {name: current_user.name}
end
应用程序.js
$.get('/current_user', function(result){
alert(result.name);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)