下面的簡單例子中將你的姓名保存為一個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.);
}
函數(shù)中間的兩行是關鍵:
var the_cookie = wm_javascript=username: + escape (the_name);
如果我在提示框中輸入了dave thau,該行代碼將生成一個字符串wm_javascript=username:dave%20thau.這就是說我將把一個名為wm_javascript的cookie保存到硬盤.該cookie的值是username:dave%20thau - 函數(shù) escape()將dave 和thau間的空格用%20做了替換.當我們讀取cookie時,我們尋找名為wm_javascript的cookie,然后提取username:dave%20thau,將其用 unescape()解碼,去掉username:.
document.cookie = the_cookie;