var t = new CookieStorage('http://abc.com/path');
t.set('name', '123', function () { });//设置
t.get('name', alert);//获取
t.remove('name', function () { });//删除
function CookieStorage(url) { this.url = url }
CookieStorage.prototype._call = function (a) {
var url = this.url + '?action=' + a.action + '&name=' + a.name;
if (a.value) url += '&value=' + encodeURIComponent(a.value);
if (a.callback) {
var call = '_' + Math.random().toString().substr(2);
url += '&callback=' + call;
window[call] = a.callback;
}
var js = document.createElement('script');
js.src = url;
document.body.appendChild(js);
}
CookieStorage.prototype.get = function (a, f) { this._call({ action: 'get', name: a, callback: f }); }
CookieStorage.prototype.set = function (a, b, f) { this._call({ action: 'set', name: a, value: b, callback: f }); }
CookieStorage.prototype.remove = function (a, f) { this._call({ action: 'remove', name: a, callback: f }); }
后端:
var m = {
get: function (req, res, url) {
res.write(url.query.callback + '(');
var v = cookie.parse(req.headers.cookie)[prefix + url.query.name];
if (v) res.write(JSON.stringify(v));
res.end(')');
},
set: function (req, res, url) {
res.setHeader('set-cookie', cookie.serialize(prefix + url.query.name, url.query.value || '', { path: url.pathname, expires: new Date(9000, 1, 1) }));
res.end(url.query.callback + '()');
},
remove: function (req, res, url) {
res.setHeader('set-cookie', cookie.serialize(prefix + url.query.name, '', { path: url.pathname, expires: new Date(2000, 1, 1) }));
res.end(url.query.callback + '()');
}
};
function (req, res) {
if (!checkReferer(req.headers.referer)) {
res.end();
return;
}
var d = url.parse(req.url, true);
var f = m[d.query.action];
if (f) f(req, res, d);
else res.end();
}