Rails - 在控制器中存储一个cookie,并从Javascript,Jquery [英] Rails - Store a cookie in controller and get from Javascript, Jquery

查看:213
本文介绍了Rails - 在控制器中存储一个cookie,并从Javascript,Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

会话值可在服务器上使用。



您可以在控制器中这样设置它们:

  session [:user_name] = @ user.name 

如果你想在javascript中访问该值,你可能需要在视图中这样做:

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






Cookie

 <$> 

在控制器中设置一个: cookies [:user_name] = @ user.name

,过期等使用Cookie的选项。)



然后可以使用jQuery访问它:

  var userName = jQuery.cookie用户名); 

注意:您也可以通过解析 document.cookie 访问使用纯javascript (不是jQuery)但是更容易让jQuery为你做(如果你已经使用那个库)。


Is it possible to store a User's Cookie or Session in Controller and Get the cookie by accessing it from JS or Jquery?

解决方案

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_tag do %>
  var userName = '<%= session[:user_name %>';
<% end %>


Cookies are managed by the browser, so accessed differently.

To set one in your controller:

cookies[:user_name] = @user.name

(You can also specify the path, expiration, etc. for the cookie using options.)

It can then be accessed using 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).

这篇关于Rails - 在控制器中存储一个cookie,并从Javascript,Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆