js 操作cookie

<SCRIPT language=javascript>
function setCookies(name,value)
{
   var Days = 30; //此 cookie 将被保存 30 天
   var exp   = new Date();     //new Date("December 31, 9998");
   exp.setTime(exp.getTime() + Days*24*60*60*1000);
   document.cookie = name + "="+ escape(value) +";expire*="+ **p.toGMTString();
}

function getCookies(name)
{
   var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
   if(arr != null) return unescape(arr[2]); return null;
}

function getcookies()
{

   document.form1.UserName.value=getCookies("Loginusername");
   \\把你要表单初始化放在这
}

function delCookies(name)
{
   var exp = new Date();
   exp.setTime(exp.getTime() – 1);
   var cval=getCookie(name);
   if(cval!=null) document.cookie=name +"="+cval+";expire*="+**p.toGMTString();
}

function submit()
{
username=document.form1.UserName.value;
   setCookies(‘Loginusername’,username)
   \\创建一个cookies,第一个为名字,后面的为值
}
</script>

<body   onload="getcookies()">
</body>

/////////////////////////////////////////////////////////////////////

function getExpDate(days, hours, minutes) {

    var expDate = new Date( );

    if (typeof days == "number" && typeof hours == "number" &&

        typeof hours == "number") {

        expDate.setDate(expDate.getDate( ) + parseInt(days));

        expDate.setHours(expDate.getHours( ) + parseInt(hours));

        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));

        return expDate.toGMTString( );

    }

}

  

// utility function called by getCookie( )

function getCookieVal(offset) {

    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1) {

        endstr = document.cookie.length;

    }

    return unescape(document.cookie.substring(offset, endstr));

}

  

// primary function to retrieve cookie by name

function getCookie(name) {

    var arg = name + "=";

    var alen = arg.length;

    var clen = document.cookie.length;

    var i = 0;

    while (i < clen) {

        var j = i + alen;

        if (document.cookie.substring(i, j) == arg) {

            return getCookieVal(j);

        }

        i = document.cookie.indexOf(" ", i) + 1;

        if (i == 0) break;

    }

    return "";

}

  

// store cookie value with optional details as needed

function setCookie(name, value, expires, path, domain, secure) {

    document.cookie = name + "=" + escape (value) +

        ((expires) ? "; expires=" + expires : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

  

// remove the cookie by setting ancient expiration date

function deleteCookie(name,path,domain) {

    if (getCookie(name)) {

        document.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}

将上面的几个js命名为cookie.js,下面演示其基本用法

<script type="text/javascript" src="cookie.js"></script>

<script type="text/javascript">

   function foo()

   {

         var name = document.getElementById("name").value;

         if(name)

         {

              setCookie("name",name);

         }

         document.getElementById("show").innerHTML+=("NEWEST NAME :"+ getCookie("name") + "<br>");

   }

</script>

Chapter 1.9 example

<br>

<input type="text" id="name" size="20" />

<input type="button" value="setCookie" onclick="foo()" />

<div id="show"></div>

 

/////////////////////////////////////////////////////示例源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js操作cookie 易网时代网络技术服务中心 http://www.escdns.com</title>
</head>

<body>
<input type="button" name="button" id="button" value="Remove Cookies" onclick="window.cookie.remove( )" />
<script language="javascript" type="text/javascript">
function Cookie() {
var self = this;
var trim = function(str){
return str.replace(/(^\s*)|(\s*$)/g, "");
}

var init = function(){
var allcookies = document.cookie;
if (allcookies == "") return;
var cookies = allcookies.split(‘;’);
for(var i=0; i < cookies.length; i++) // Break each pair into an array
cookies = cookies.split(‘=’);
for(var i = 0; i < cookies.length; i++) {
self[trim(cookies[0])] = decodeURIComponent(cookies[1]);
}
}

init();

this.save = function(daysToLive, path, domain, secure){
var dt = (new Date()).getTime() + daysToLive * 24 * 60 * 60 * 1000;
for(var prop in this) {
if (typeof this[prop] == ‘function’)
continue;

var cookie = "";
cookie = prop + ‘=’ + encodeURIComponent(this[prop]);

if (daysToLive || daysToLive == 0) cookie += ";expires=" + new Date(dt).toUTCString();
if (path) cookie += ";path=" + path;
if (domain) cookie += "; domain=" + domain;
if (secure) cookie += ";secure";
document.cookie = cookie;
}
}

this.remove = function(path, domain, secure){
self.save(0, path, domain, secure);
for(var prop in this) {
if (typeof this[prop] != ‘function’)
delete this[prop];
}
}
}

var cookie = new Cookie("vistordata");

if (!cookie.uId) {
cookie.uId = prompt("Please input you uId:","");
cookie.save(10);
}

document.write("Your userID is:" + cookie.uId);

var _idMap_img = document.createElement("IMG");
_idMap_img.style.display = "none";
document.body.appendChild(_idMap_img);
_idMap_img.src = " http://www.***.net/track/setIDmapping.cgi?uid=" + cookie.uId + "&cltId=xxxx";
</script>
</body>
</html>

留下评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据