Here's a little thing I came up with, which hopefully can make reading/writing cookies with JavaScript easier.
这是我想到的一件事,希望可以使使用JavaScript读取/编写cookie更加容易。
好主意 (The big idea)
The idea is to keep a JavaScript object (a hash array) of all little variable things you want to store in a cookie. Then, once ready, you encode the object into a JSON string and save it to a cookie. To load the data from a previously saved cookie, you decode the JSON string back into an object.
这个想法是保留一个JavaScript对象(一个哈希数组),该对象包含要存储在cookie中的所有小变量。 然后,一旦准备好,就可以将该对象编码为JSON字符串并将其保存到cookie。 要从以前保存的cookie加载数据,您可以将JSON字符串解码回一个对象。
微小的实现 (The tiny implementation)
Having the little JSON lib from json.org, it's very easy. The solution was to have an object called prefs
(the idea initially came when I wanted to save user preferences), which has:
从json.org获得小JSON库,这非常容易。 解决方案是创建一个名为prefs
的对象(这个想法最初是在我想保存用户首选项时出现的),该对象具有:
data
attribute - stores the data you want to save,data
属性-存储要保存的数据,save()
method, andsave()
方法,以及load()
method.load()
方法。
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();
}
}
使用prefs对象 (Using the prefs object)
In order to use this you need to satisfy dependencies first, including json.js and prefs.js:
为了使用它,您需要首先满足依赖关系,包括json.js和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()和load()了。 如果您需要删除Cookie,请调用带有过去日期的save()。 这里有些例子:
// 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);
谢谢 (Thanks)
Thank you for reading! As always, any comments are appreciated.
感谢您的阅读! 与往常一样,任何评论都值得赞赏。
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息