下面的简单例子中将你的姓名保存为一个cookie:
function setCookie()
{
var
the_name = prompt("What's your name?","");
var the_cookie =
"wm_javascript=username:" + escape(the_name);
document.cookie =
the_cookie;
alert("Thanks, now go to the next
page.");
}
函数中间的两行是关键:
var the_cookie = "wm_javascript=username:" + escape (the_name);
如果我在提示框中输入了"dave thau",该行代码将生成一个字符串wm_javascript=username:dave%20thau.这就是说我将把一个名为wm_javascript的cookie保存到硬盘.该cookie的值是username:dave%20thau - 函数 escape()将"dave" 和"thau"间的空格用%20做了替换.当我们读取cookie时,我们寻找名为wm_javascript的cookie,然后提取username:dave%20thau,将其用 unescape()解码,去掉username:.
document.cookie = the_cookie;
更多信息请查看IT技术专栏