creating an object in js

Subject:

reference: https://www.phpied.com/json-javascript-cookies/The code is as follows:

var prefs = { data: {}, load: function () { var the_cookie = document.cookie.split(';'); if (the_cookie[0]) { this.data = unescape(the_cookie[0]).parseJSON(); } return this.data; }, save: function (expires, path) { var d = expires || new Date(2020, 02, 02); var p = path || '/'; document.cookie = escape(this.data.toJSONString()) + ';path=' + p + ';expires=' + d.toUTCString(); } }

Using the prefs object

In order to use this you need to satisfy dependencies first, including json.js and prefs.js:

<script type="text/javascript" src="json.js"></script> <script type="text/javascript" src="prefs.js"></script>

Then you're ready to do save()s and load()s. If you need to delete a cookie, you call save() with date in the past. Here are some examples:

// save prefs.data.something = "one"; // save one // ... do other stuff ... prefs.data.another = "two"; // ready to store? prefs.save(); // another syntax var to_save = { one: 1, two: 2, } prefs.data = to_save; prefs.save(); // delete var date_in_the_past = new Date(2000,02,02); prefs.save(date_in_the_past); // read var what = prefs.load(); // load populates prefs.data and also returns alert(what.something); // or ... alert(prefs.data.something);

2018-01-16 10:30:36gstlouis