使用jQuery访问会话变量

我需要在rails中呈现HTML元素,具体取决于是否设置了会话变量。 有可能做这样的事吗?

Session是服务器端,我不是rails开发人员,但是在asp.net mvc中我做了一个ajax调用,获取Session值并将其返回给客户端。 只是一个想法。

您无法从客户端访问任何服务器端变量。 您基本上可以在javascript变量中呈现会话变量值,并在jquery中在客户端使用它。

一个小型库,可以帮助您阅读写入cookie。

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; } }; }()); 

用法:

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

你可以在rails中渲染js视图并将会话变量放在那里。 有关mo信息,请参阅http://railscasts.com/episodes/205-unobtrusive-javascript

如果您使用rails 3并使用cookie存储存储会话变量,那么您应该能够使用JS访问会话变量,就像访问典型的cookie一样。