jsonp+cookie实现数据跨域共享

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();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值