下面的简单例子中将你的姓名保存为一个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;