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

前端 未结 1 1658
甜味超标
甜味超标 2021-02-06 16:29

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

1条回答
  •  情话喂你
    2021-02-06 17:14

    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).

    0 讨论(0)
提交回复
热议问题