下面的簡單例子中將你的姓名保存為一個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ù)中間的兩行是關(guān)鍵:
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做了替換.當(dāng)我們讀取cookie時(shí),我們尋找名為wm_javascript的cookie,然后提取username:dave%20thau,將其用 unescape()解碼,去掉username:.
document.cookie = the_cookie;
更多信息請查看IT技術(shù)專欄