在搞Web2.0,使用惯了Ajax与服务器进行交互,没考虑过javascript如何在客户端保存数据。最近在做原型的时候发现如果javascript要在客户端保存数据还是很麻烦的事情。例如在页面左边的一个二级菜单,我如何在刷新页面的时候还保持我所选择的状态。
javascript与cookies的交互:
<SCRIPT language=javascript>
function set_cookie (name, value) {
var argv = set_cookie.arguments;
var argc = set_cookie.arguments.length;
var expires = new Date();
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
expires.setYear(4002);
expires.setMonth(10);
expires.setDate(1);
expires.setHours(2);
expires.setMinutes(3);
st = name+"="+escape (value)+"; expires=" + expires.toGMTString()+ ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) ;
document.cookie =st;
}
function get_cookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
offset=j;
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape (document.cookie.substring(offset, endstr));
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
break;
}
return null;
}
function del_cookie(name) {
var expdate = new Date ();
expdate.setTime (expdate.getTime()-1);
set_cookie (name, "", expdate)
}
</SCRIPT>