原生js--cookie

1、本地存储方式的补充:

flash cookie ,用于flash,最大不超过100k,借助flash的ExternalInterface接口,可以实现js对flash cookie的操作

google gears, 是google开发的一款浏览器插件,内嵌SQLite数据库,并提供了api对其进行操作,但已被废弃

indexedDB,目前在firefox中有实现,同cookie等存储方式相比,它可以存储多种类型的数据

 

2、cookie

1、cookie的值中不允许包含分号、逗号和空白符,在存储之前最好使用encodeURIComponent方法对其进行编码,读取时再进行解码

2、和jQuery中不同的是,原生操作cookie设置过期时间使用的秒(s)而不是天(d)

3、设置cookie

function setCookie( name, value, time ){
    var cookie = name + "=" + encodeURIComponent( value );
    if( typeof time === "number" ){
        cookie += "; max-age=" + time;
    }
    document.cookie = cookie;
}

4、获取全部cookie并保存到对象当中:

function getCookie(){
    var cookie = {};
    var all = document.cookie;
    if( all === "" ){
        return cookie;
    }
    var list = all.split( "; " );
    for( var i=0; i<list.length; i++ ){
        var singleCookie = list[i];
        var p = singleCookie.indexOf( "=" );
        var name = singleCookie.substring( 0, p );
        var value = singleCookie.substring( p+1 );
        value = decodeURIComponent( value );
        cookie[name] = value
    }
    return cookie;
}

posted @ 2014-03-06 09:31  charling  阅读(746)  评论(0编辑  收藏  举报