common.js 2.18 KB
/**
 * 页面公共逻辑和接口
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/11/23
 */
var $ = require('jquery');

function cookie(name) {
    var cookies = document.cookie,
        cookieVal,
        offset;

    if (document.cookie && document.cookie !== '') {
        offset = cookies.indexOf(name + '=');
        if (offset > -1) {
            offset += name.length + 1;

            cookieVal = decodeURIComponent($.trim(cookies.substring(offset, cookies.indexOf(';', offset))));
        }
    }

    return cookieVal;
}

function setCookie(name, value, options) {
    var expires = '',
        path,
        domain,
        secure,
        date;

    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }

        if (options.expires &&
            (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
}

function getUser() {
    var c = cookie('_UID'),
        user;

    if (typeof c === 'undefined') {
        return 0;
    }

    user = c.split('::');

    if (typeof user === 'undefined' || user.length < 4) {
        return 0;
    }

    return user;
}

function getUid() {
    var user = getUser();

    if (user === 0) {
        return 0;
    }

    return user[1];
}

function getShoppingKey() {
    var c = cookie('_g');

    if (typeof c === 'undefined') {
        return '';
    }

    return JSON.parse(c).k;
}

window.cookie = cookie;

window.setCookie = setCookie;

window.getUser = getUser;

window.getUid = getUid;

window.getShoppingKey = getShoppingKey;