开发者

Access session variable using jQuery

开发者 https://www.devze.com 2023-03-27 02:57 出处:网络
I need to render an HTML element in rails, d开发者_如何转开发epending upon whether a session variable is set or not. Is it possibleto do something like this?Session is server side, I am not a rails de

I need to render an HTML element in rails, d开发者_如何转开发epending upon whether a session variable is set or not. Is it possible to do something like this?


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.


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.


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");


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号