我如何在jquery设置的rails中读取cookie [英] How can i read cookies in rails that have been set by jquery
问题描述
我正在像这样在jquery中设置一个cookie(可以正常工作,并且生成了cookie):
I am setting a cookie in jquery like this(works fine and the cookie is generated):
$(document).ready(function() {
var consp = $("input[home]").attr("home");
$("input[name='commit']").click(function() {
$.cookie('home', consp);
});
});
在我的控制器中,我试图获取该cookie值.所以我正在使用标准的Cookie读取方式
In my controller i am trying to get hold of that cookies value. So i am using standard READing of cookies like this
def some_method
@value = cookies[:home]
end
但是当我输出@value的值时,什么也不会返回.仅当我使用jquery设置cookie时才会发生这种情况,但是如果我直接通过rails(不使用jquery)设置cookie则不会发生.关于为什么会发生这种情况有任何想法吗?谢谢
But when i output the value of @value, nothing is returned. This only happens if i set the cookie using jquery, however does not happen if i set the cookie directly through rails(no jquery). Any thoughts as to why this occurs? thanks
推荐答案
好吧,弄清楚了这一点:
Ok, figured this one out:
我在提交表单时创建了这个cookie,并且由于mvc架构的缘故,rails提交了一个create操作,并在成功重定向后重定向回原始页面.因此,我需要此Cookie在所有页面上均有效,因此 jquery.cookie插件.
I was creating this cookie when i was submitting a form and due to the mvc architecture, rails was submitting to a create action and the redirecting back to orginal page upon successfull redirect. So i needed this cookie to be valid across all pages so jquery.cookie plugin.
解决方案是像这样将path参数传递给混合
The solution was to pass the path parameter into the mix like this
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
然后,它允许从所有页面路由读取cookie.
This then allows the cookie to be read from all page routes.
这篇关于我如何在jquery设置的rails中读取cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!