Access session variable using jQuery

老子叫甜甜 提交于 2019-12-10 13:54:33

问题


I need to render an HTML element in rails, depending upon whether a session variable is set or not. Is it possible to do something like this?


回答1:


Session is server side, I am not a rails developer, but in asp.net mvc I made an ajax call that gets the Session value and returns it back to client. Just an idea.




回答2:


You cannot access any server side variable from client side. You can basically render the session variable value in a javascript variable and use it on the client side in jquery.




回答3:


A small library that helps you read write cookies.

var cookieHelper = (function () {
    return {
        createCookie: function (name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        writeSessionCookie: function (cookieName, cookieValue) {
            document.cookie = cookieName + "=" + cookieValue + "; path=/";
        },
        readCookie: function (name) {
            var nameEq = name + "=";
            var ca = document.cookie.split(';');
            var i;

            for (i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
                if (c.indexOf(nameEq) === 0) { return c.substring(nameEq.length, c.length); }
            }

            return null;
        },
        deleteCookie: function (name) {
            this.createCookie(name, null, -1);
        },
        testSessionCookieEnabled : function() {
           document.cookie ="testSessionCookie=Enabled";
            if (getCookieValue ("testSessionCookie")=="Enabled")
              return true 
            else
              return false;
        }
    };
 }());

Usage:

if(cookieHelper.testSessionCookieEnabled)
{
  cookieHelper.writeSessionCookie("test","session");
}
else
{
  //do something
}

var cookieValue=cookieHelper.readCookie("test");



回答4:


you can render js view in rails and put there session variable. for mo info see http://railscasts.com/episodes/205-unobtrusive-javascript




回答5:


If you are using rails 3 and storing your session variables using cookie store, then you should be able to access the session variables using JS just like accessing a typical cookie.



来源:https://stackoverflow.com/questions/7005751/access-session-variable-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!