//創(chuàng)建和存儲cookie
function setCookie(c_name,value,expiredays)
{
//獲取日期的對象
var exdate = new Date();
//設(shè)置過期過期的日期
exdate.setDate(exdate.getDate() + expiredays);
//escape(),十六進制ASCII編碼勤众,一般用于中文發(fā)送解決亂碼問題——解碼則用unescape
//寫入cookie的值
document.cookie = c_name + '=' + escape(value) +
((expiredays == null) ? '' : ";_expires=" + exdate.toGMTString());
}
//檢查是否已經(jīng)設(shè)置cookie
function getCookie(c_name)
{
? ? ? ?//檢查是否存在cookie
? ? ? if(document.cookie.length>0)
? ? ?{
? ? ? ? ? c_start = document.cookie.indexOf(c_name + "=");
? ? ? ? ? ?if(c_name != -1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? ?c_name = c_start + c_name.length + 1;
? ? ? ? ? ? ? ? ? //從c_start開始檢索锉矢,返回 “ 际乘;” 的位置
? ? ? ? ? ? ? ? ? c_end = document.cookie.indexOf(";",c_start);
? ? ? ? ? ? ? ? ? //處理沒有檢測到“ ; ”的異常
? ? ? ? ? ? ? ? ? ?if(c_end == -1) c_end = document.cookie.length;
? ? ? ? ? ? ? ? ?//返回cookie中截取存入的值,并用unescape()解碼
? ? ? ? ? ? ? ? ? ?return unescape(document.cookie.substring(c_start,c_end));
? ? ? ? ? ? ? ?}
? ? ? ? ? }
? ? ? ? ? return "";
}
//cookie 的用法
function checkCookie()
{
? ? ? ? ?username = getCookie('username');
? ? ? ? ? if(username != null && username != "")
? ? ? ? ? {
? ? ? ? ? ? ? ? alert('Welcome again' + username + '!');
? ? ? ? ? ? }
? ? ? ? ? ?else
? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?//提示框姻僧,輸入username
? ? ? ? ? ? ? ? ? ? username = prompt('Please enter your name:',"");
? ? ? ? ? ? ? ? ? ?if(username != null && username != "")
? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ?setCookie('username',username,10);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? }
}