web存储方法,现成代码
1.cookie的设置与取用
function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { return c.substring(name.length,c.length); } } return ""; } function checkCookie(){ var user=getCookie("username"); if (user!=""){ alert("欢迎 " + user + " 再次访问"); } else { user = prompt("请输入你的名字:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } }
2.localStorage、sessionStorage的设置与使用
//保存数据
function save(){
var site = new Object;
site.keyname = document.getElementById("keyname").value;
site.sitename = document.getElementById("sitename").value;
site.siteurl = document.getElementById("siteurl").value;
var str = JSON.stringify(site); // 将对象转换为字符串
localStorage.setItem(site.keyname,str);
alert("保存成功");
}
//查找数据
function find(){
var search_site = document.getElementById("search_site").value;
var str = localStorage.getItem(search_site);
var find_result = document.getElementById("find_result");
var site = JSON.parse(str);
find_result.innerHTML = search_site + "的网站名是:" + site.sitename + ",网址是:" + site.siteurl;
}