jQuery 操作cookie保存用户浏览信息

时间:2022-12-01 20:16:37
使用jQuery操作cookie之前需要引入jQuery的一个cookie小组件js,代码如下:
 
/*
        jQuery cookie plugins
*/

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            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(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
 
然后开始在页面写操作cookie存储用户信息js函数(方法),保存时间为两年,例子如下:
 
// 写入cookie
function writeHistoryCookie() {
        var formatJson = {"data":[]};
        var jsonCookie = {"screen_name":escape(screen_name),"screen_ico":escape(screen_ico),"screen_location":escape(screen_location),
                        "screen_score":escape(screen_score),"userid":escape(userid)};
        
        // parameters value is null? string return
        if(!jsonCookie.userid){
                showHistory();
                return;
        }
        //read all history
        var objs = $j.cookie('historyCooike');
        var arrayCookies = [];
        var jsonObjs = null;
        if(objs != null){
                                 // 值得注意的是,json转字符串和字符串转json的使用方法一定要清楚并检测是否兼容浏览器
                jsonObjs = jQuery.parseJSON(objs);
                for(var i=0;i<jsonObjs.data.length;i++){
                        var js_name = unescape(jsonObjs.data[i].screen_name);
                        var js_ico = unescape(jsonObjs.data[i].screen_ico);
                        var js_id = unescape(jsonObjs.data[i].userid);
                        var js_location = unescape(jsonObjs.data[i].screen_location);
                        var js_score = unescape(jsonObjs.data[i].screen_score);
                        if(userid != js_id){
                                var temp = {"screen_name":escape(js_name),"screen_ico":escape(js_ico),"screen_location":escape(js_location),
                                                                "screen_score":escape(js_score),"userid":escape(js_id)};
                                formatJson.data.push(temp);
                        }
                }
        }
        if(formatJson.data.length > 9){
                formatJson.data.pop();//delete last one
        }
        //put to first
        formatJson.data.unshift(jsonCookie);
        //get string type json
        jsonObjs = JSON.stringify(formatJson);
        //writer
        $j.cookie('historyCooike', jsonObjs , {expires: 365 * 2, path: '/'});
        //writer over show
        showHistory();
}
 
// 读取cookie
function showHistory() {
        var str='';
        var historyCooike = $j.cookie('historyCooike');
        var cookieObjs = null;
        if(historyCooike != null){
                cookieObjs = jQuery.parseJSON(historyCooike);
                for(var i=0;i<cookieObjs.data.length;i++){
                        var cookie_name = unescape(cookieObjs.data[i].screen_name);
                        var cookie_ico = unescape(cookieObjs.data[i].screen_ico);
                        var cookie_id = unescape(cookieObjs.data[i].userid);
                        var cookie_location = unescape(cookieObjs.data[i].screen_location);
                        var cookie_score = unescape(cookieObjs.data[i].screen_score);
                        if(cookie_id == null || cookie_id == 'undefined') continue;
                        str +=  '<li>' +
                              '<div class="imgPL">' +
                                '<a class="blue" href="profile.do?uid=' + cookie_id + '">' +
                                   '<img border="0" src="' + cookie_ico + '">' +
                                '</a>' +
                              '</div>' +
                             '<p>' +
                              '<span><a href="profile.do?uid=' + cookie_id + '">' + cookie_name + '</a></span> [' + cookie_location + ']'+
                               '<br />'+
                                          '微博价值:<em class="red">' + cookie_score + '</em>'+
                            '</p>'+
                                '</li>'
        }
        }
        if(str == '') {
                $j('#right_user_list').html('<li style="text-align:center; line-height:40px; color:#646464; font-size:12px; border:none; padding-bottom:0px;">暂无查询记录</li>');
        }else{
                str += '<div style=" text-align: right; color:#0691C4; cursor:pointer; padding-top: 7px; font-size: 12px; padding-right:10px;"><span id="clearJL" onclick="clearCookie()">清空记录>>></span></div>';
                $j('#right_user_list').html(str);
        }
}
 
// 清除cookie
function clearCookie(){
        $j.cookie('historyCooike', null);
        showHistory();
}