cookie及浏览器保存(localStorage)

cookie及浏览器保存(localStorage)_第1张图片

存cookie

//保存中文信息到Cookie, 要使用UrlEncode编码

var cookie = new HttpCookie("info");

cookie.Value = Server.UrlEncode("中文信息-" + DateTime.Now.ToString());

cookie.Expires = DateTime.Now.AddMinutes(1); //只保留1分钟

Response.SetCookie(cookie);//必须写不然cookie没保存

//过期时间改到5天之前,立即过期,因此也清除此cookie的方法

cookie.Expires = DateTime.Now.AddDays(-5);

取cookie

HttpCookie cookie = Request.Cookies["info"]; //根据名称直接查找cookie、

localStorage

if (!window.localStorage) {

                alert("浏览器不支持localstorage");

                return false;

}

3中写入方法

(可以不new  var storage = window.localStorage;)

//写入a字段

localStorage["a"] = 6;

//写入b字段

localStorage.b = 7;

//写入c字段

localStorage.setItem("c", 8);

简单的例子:

localStorage.setItem(“name”,“panda”);//设置name为panda

localStorage.setItem(“name”,“Jane”);//覆盖之前的值,现在name所对应的值是Jane

localStorage.getItem(“name”);//获取name的值,即Jane

localStorage.removeItem(“name”);//删除name以及name的值

localStorage.clear();//清除localstorage里边所有数据

function forEachKey(callback) {//遍历显示localStorage中的key

  for (var i = 0; i < localStorage.length; i++) {

    callback(localStorage.key(i));

  }

}

你可能感兴趣的:(cookie及浏览器保存(localStorage))