用java写cookies的几个函数

2008-04-09 03:59:14来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

函数一、写cookie的函数,将Cookie写入客户端,通用函数,传入3个参数即可(Cookie名字,值和失效期)
//函数:写入cookie
function WriteCookie (cookieName, cookieValue, expiry)
{
var expDate = new Date();
if(expiry) //如果设置了cookie失效时间;
{
expDate.setTime (expDate.getTime() expiry);
document.cookie = cookieName "=" escape (cookieValue) "; expires=" expDate.toGMTString();
}
else //没有设置cookie失效时间;
{
document.cookie = cookieName "=" escape (cookieValue);
}
}

函数二、取得表单数据
//函数:取得form表单域的值作为cookie的相关值(cookie name,cookie value,expires)
function setCookie ()
{
var name = document.myform.text1.value;
var value = document.myform.text2.value;
var num = document.myform.text3.value;
var select = document.myform.text3.selectedIndex;
if (name=="" || value=="" || num==""){
alert ("请输入Cookie的名字,值和失效期再测试!");
return false;
}

if(num == 0)
{
WriteCookie(name, value, 0);
}
else if(select == 0)
//如果选择的是天;时间换算成秒;
{
WriteCookie(name, value, 1000 * 60 * 60 * 24 * num);
}
else if(select == 1)
//如果选择的是月;
{
WriteCookie(name, value, 1000 * 60 * 60 * 24 * num * 31);
}
else if(select == 2)
//如果选择的是年;
{
WriteCookie(name, value, 1000 * 60 * 60 * 24 * num * 365);
}
alert ("Cookie已经保存")
}

函数三、读cookie的值
function ReadCookie (CookieName) {
var CookieString = document.cookie;
var CookieSet = CookieString.split (';');
var SetSize = CookieSet.length;
var CookiePieces
var ReturnValue = "";
var x = 0;
for (x = 0; ((x < SetSize) && (ReturnValue == "")); x ) {

CookiePieces = CookieSet[x].split ('=');

if (CookiePieces[0].substring (0,1) == ' ') {
CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
}

if (CookiePieces[0] == CookieName) {
ReturnValue = CookiePieces[1];

}

}

alert ("Cookie Value is:" ReturnValue);

}


HTML表单内容:
<form name=myform>
<table width="95%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Cookie name:</td>
<td>
<input type=text name="text1" value="java2000" readonly>
</td>
</tr>
<tr>
<td>Cookie value:</td>
<td>
<input type=text name="text2" value="welcome" readonly>
</td>
</tr>
<tr>
<td>Cookie保留期:</td>
<td>
<input type=text value=0 name="text3">
<select name="Choice">
<option value="0" selected>天</option>
<option value="1">月</option>
<option value="2">年</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type=button value="保存Cookie" onClick="setCookie()" name="button2">
<input type=button value="删除Cookie"
onClick="WriteCookie(document.myform.text1.value, '');alert('Cookies已经清除了!')" name="button">
<input type="submit" name="Submit" value="看Cookie内容" onClick="ReadCookie (document.myform.text1.value)">
</td>
</tr>
</table>
</form>
说明:具体使用时可能需要你稍微修改一下以适合自己的应用,但是主要代码已经在这里了。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:WIN下动态注册码实现方法

下一篇:perl程序设计(三)