日期:2014-05-16  浏览次数:20491 次

通过JS读、写cookie

//写入cookie

function writeCookie(name, value, hours)

{

? var expire = "";

? if(hours != null)

? {

??? expire = new Date((new Date()).getTime() + hours * 3600000);

??? expire = "; expires=" + expire.toGMTString();

? }

? document.cookie = name + "=" + escape(value) + expire;

}

?

//读取cookie

//方法 1

function readCookie(name)

{

? var cookieValue = "";

? var search = name + "=";

? if(document.cookie.length > 0)

? {

??? offset = document.cookie.indexOf(search);

??? if (offset != -1)

??? {

????? offset += search.length;

????? end = document.cookie.indexOf(";", offset);

????? if (end == -1) end = document.cookie.length;

????? cookieValue = unescape(document.cookie.substring(offset, end))

??? }

? }

? return cookieValue;

}

?

//方法2

function getCookie(name)
{
??? var?myCookie = document.cookie;
??? name += "=";
??? var i = 0;
??? while (i < myCookie.length)
??? {
????? var offset = i + name.length;
????? if (myCookie.substring(i, offset) == name)
????? {
??????? var endstr = myCookie.indexOf(";", offset);
??????? if (endstr == -1) endstr = myCookie.length;
????????? return unescape(myCookie.substring(offset, endstr));
????? }
??????? i = myCookie.indexOf(" ", i) + 1;
??????? if (i == 0) break;
??? }
??? return null;
}