简体   繁体   English

Rails - 将cookie存储在控制器中并从Javascript,Jquery获取

[英]Rails - Store a cookie in controller and get from Javascript, Jquery

是否可以在Controller中存储用户的Cookie或会话,并通过从JS或Jquery访问cookie来获取cookie?

Session values are available on the server. 会话值在服务器上可用。

You can set them like this in your controller : 您可以在控制器中将它们设置为:

session[:user_name] = @user.name

If you want to access that value later in javascript, you'll probably want to do something like this in a view: 如果您想稍后在javascript中访问该值,您可能希望在视图中执行以下操作:

<%= javascript_tag do %>
  var userName = '<%= session[:user_name %>';
<% end %>

Cookies are managed by the browser, so accessed differently. Cookie由浏览器管理,因此访问方式不同。

To set one in your controller: 要在控制器中设置一个:

cookies[:user_name] = @user.name

(You can also specify the path, expiration, etc. for the cookie using options .) (您还可以使用选项指定cookie的路径,到期时间等。)

It can then be accessed using jQuery: 然后可以使用jQuery访问它:

var userName = jQuery.cookie("user_name");

Note: you can also access the cookie using pure javascript (not jQuery) by parsing document.cookie , but it is much easier to let jQuery do it for you (if you're already using that library). 注意:你也可以通过解析document.cookie 使用纯javascript (而不是jQuery)来访问cookie ,但是让jQuery为你做这件事容易得多 (如果你已经在使用那个库)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM