Why jQuery.cookie returns “[object Object]” for a single string value

后端 未结 5 1469
故里飘歌
故里飘歌 2021-01-26 11:40

I set a cookie on Rails like this,

cookies[:account] = { :value => @account.to_s, :expires => 3.month.from_now }

Which seems to be workin

相关标签:
5条回答
  • 2021-01-26 11:50

    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:-

    • Same cookie name but at a different path
    • I found passing the parameters for path/expiry, that the plugin was sometimes treating this as if I were setting a value, and it was trying to set a JSON-like object with path and expiry as the value.
    • Loading the script twice with the cookie set code running on load
    • AJAX loaded content refreshing the script can cause this issue to occur.

    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.

    I hope this helps someone else, and saves them from the hours of frustration that I had!

    0 讨论(0)
  • 2021-01-26 11:58

    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). This can lead $.cookie() to return [object Object]

    0 讨论(0)
  • 2021-01-26 11:58

    You can use Mozilla Library. You'll be able to set and get cookies like this

    docCookies.setItem(name, value);
    docCookies.getItem(name);
    
    0 讨论(0)
  • 2021-01-26 12:14

    [object Object] is the return value from Object.toString(), so that means that $.cookie('account') is returning a non-Number, non-String object.

    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"));
    
    0 讨论(0)
  • 2021-01-26 12:14

    Cookie has a maximum size of 4kb only. That could be one of the reasons.

    As for my case. It certainly exceeds 4kb looking at the data alone.

    My alternative though is using localStorage.

    0 讨论(0)
提交回复
热议问题