WEB开发网
开发学院网页设计JavaScript JS操作Cookie 大全 阅读

JS操作Cookie 大全

 2009-06-30 04:02:00 来源:WEB开发网   
核心提示: 将上面的几个js命名为cookie.js,下面演示其基本用法<script type="text/javascript" src="cookie.js"></script><script type="text/jav

将上面的几个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%3c/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[i] = cookies[i].split('=');
for(var i = 0; i < cookies.length; i++) {
self[trim(cookies[i][0])] = decodeURIComponent(cookies[i][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>

上一页  1 2 

Tags:JS 操作 Cookie

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接