问题
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