[英]Why jQuery.cookie returns “[object Object]” for a single string value
I set a cookie on Rails like this, 我像这样在Rails上设置一个cookie,
cookies[:account] = { :value => @account.to_s, :expires => 3.month.from_now }
Which seems to be working fine, a simple debug @account
shows 似乎工作正常,显示一个简单的
debug @account
--- myvalue
…
But when calling the cookie using jQuery.Cookie It return a "[object Object]"
instead. 但是,当使用jQuery.Cookie调用cookie时,它将返回
"[object Object]"
。
> $.cookie('account');
"[object Object]"
Any idea why is this happening and how to solve it? 知道为什么会这样以及如何解决吗?
I know I am pretty late to the answers here, but just thought I would post my solution on this too. 我知道我对这里的答案很晚了,但是只是想我也将对此发布解决方案。 I battled for hours with this issue of jQuery Cookie returning [object Object], and found some possible cases that would cause this:-
我与这个问题的jQuery Cookie返回[object Object]进行了数小时的奋斗,并发现了可能导致这种情况的一些情况:
In the end, I decided to use the localStorage option as my data being stored was very small, and not worth the time wasted trying to get jQuery cookie to work. 最后,我决定使用localStorage选项,因为我存储的数据非常小,不值得浪费时间让jQuery cookie正常工作。
I hope this helps someone else, and saves them from the hours of frustration that I had! 我希望这可以帮助其他人,并将他们从我遭受的挫折中解救出来!
To anyone else that runs into this, check to make sure you don't have multiple cookies of the same name (with different paths or expirations). 对于遇到此问题的其他任何人,请检查以确保您没有多个同名的Cookie(具有不同的路径或有效期)。 This can lead $.cookie() to return
[object Object]
这可能导致$ .cookie()返回
[object Object]
[object Object]
is the return value from Object.toString()
, so that means that $.cookie('account') is returning a non-Number, non-String object. [object Object]
是Object.toString()
的返回值,这意味着$ .cookie('account')返回一个非Number,非String的对象。
On way to start figuring out what's in the return value (in an effort to help you determine what's in the object returned) is to loop over the properties to figure it out. 开始弄清楚返回值中的内容(以帮助您确定返回的对象中的内容)的方法是遍历属性以弄清楚。
So, like this: 因此,像这样:
var obj = $.cookie('account');
var msg = [];
for(var i in obj) msg.push( i +" = " + obj[i]);
alert(msg.join("\n")); // or console.log(msg.join("\n"));
You can use Mozilla Library . 您可以使用Mozilla库 。 You'll be able to set and get cookies like this
您将可以设置和获取这样的Cookie
docCookies.setItem(name, value);
docCookies.getItem(name);
Cookie has a maximum size of 4kb only. Cookie的最大大小仅为4kb。 That could be one of the reasons.
这可能是原因之一。
As for my case. 至于我的情况。 It certainly exceeds 4kb looking at the data alone.
单看数据肯定超过4kb。
My alternative though is using localStorage. 我的替代方法是使用localStorage。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.