简体   繁体   中英

jquery cookie plugin/ read write cookie

I have build couple of functions using jquery cookie plugin, I am having issue with making it work cross pages.

I have set.html page which sets cookies, and show.html which shows pages. Everytime someone views set.html random key value pair is added to the cookie.

When I log the data set.html looks like cookies are set and stored correctly, but when I go to show.html only first key/value is retrieved. I try to use path, which still didn't work.

function savePage(ID, name){
  deleteAllCookies();
  $.cookie.json = true;
  var idContainer = ($.cookie('the_cookie_key_3')) || [];
  var idContainerVal = ($.cookie("the_cookie_key_val_3")) || {};
  console.log(typeof idContainer);
  console.log(idContainerVal);
  if (idContainer.indexOf(ID) === -1) { idContainer.push(ID); idContainerVal[ID] = name;}

  $.cookie('the_cookie_key_3', idContainer, { expires: 40});
  $.cookie('the_cookie_key_val_3', idContainerVal, { expires: 40 });
    console.log(idContainerVal);
}

function getSavedPages(){
    $.cookie.json = true;
    var idContainer = ($.cookie('the_cookie_key_val_3')) || {};
    console.log(idContainer);
    return idContainer;
} 

In your second function, don't pass $.cookie() any arguments. You're telling it to give you the_cookie_key_val_3 .

Also, line 4 (and similarly line 5) should be something like this:

var idContainer = $.cookie('the_cookie_key_3') || '';

Because the result of $.cookie(string) returns a JSON string, or undefined .

And of course, remove all console.log() statements before using code in production!

The time you have set the cookie to expire is too short. Hence it would not be able to live long enough to capture it in other pages.

Using cookie to save data can be tricky. From my experience it worked on just the pages that was open when i started running the server. Instead of using cookies use localStorage. LocalStorage allows you to set the key and value.

localStorage.setItem("data", the_cookie_key_3)

Where the key is data and value is the_cookie_key_3

You can retrieve the data by using localStorage.getItem("data");

I made it work without using jquery cookie, instead I used combination cookie and local storage. Here is the code

if (!window.localStorage) {
  window.localStorage = {
    getItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },
    key: function (nKeyId) {
      return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
    },
    setItem: function (sKey, sValue) {
      if(!sKey) { return; }
      document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
      this.length = document.cookie.match(/\=/g).length;
    },
    length: 0,
    removeItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
      this.length--;
    },
    hasOwnProperty: function (sKey) {
      return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
    }
  };
  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}


function getSavedPages() {
  var page = window.localStorage.getItem('hashStoreKeyValues');
  if(page==null){
   return [];
  } 
    var idContainer = JSON.parse(unescape(page));
    return  idContainer;
}

function savePage(ID, name) {

   var currentStatus =  JSON.parse(unescape(window.localStorage.getItem('hashStoreKeys')));
   var currentStatusValues =  JSON.parse(unescape(window.localStorage.getItem('hashStoreKeyValues')));
   if(currentStatus == null){
      currentStatus = [];
   } 

   if(currentStatusValues == null){
      currentStatusValues = {};
   } 

   if (currentStatus.indexOf(ID) === -1) { 
      currentStatus.push(ID); 
      currentStatusValues[ID] = name;
   }
   window.localStorage.setItem("hashStoreKeys", JSON.stringify(currentStatus));
   window.localStorage.setItem("hashStoreKeyValues", JSON.stringify(currentStatusValues));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM