家园
个人
文集
http://
www
.
5x54
.
com
JavaScript:cookie 设置与读取
作者:
网上收集
点击:
读取中...
次
引用代码:
<html>
(%$$#^66967*&%2)我型我塑www.5x54.com
<head><title>cookie的参数</title>
(%$$#^66967*&%2)我型我塑www.5x54.com
<script language="javascript">
(%$$#^66967*&%2)我型我塑www.5x54.com
function setCookie()
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
var value=prompt("请输入cookie变量的值",""); //接收用户输入的值
(%$$#^66967*&%2)我型我塑www.5x54.com
if(value!=null) //判断value是否为空
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
var expiration = new Date((new Date()).getTime() + 10 * 60000);//设置cookie存活期
(%$$#^66967*&%2)我型我塑www.5x54.com
document.cookie = "username=" + escape(value)+ "";//给cookie编码
(%$$#^66967*&%2)我型我塑www.5x54.com
xpires ="+ expiration.toGMTString()+";path="/";domain="local host"; secure=""; //设路径
(%$$#^66967*&%2)我型我塑www.5x54.com
alert("设置cookie值成功编码结果为:username="+escape(value));//输出结果
(%$$#^66967*&%2)我型我塑www.5x54.com
}else{
(%$$#^66967*&%2)我型我塑www.5x54.com
alert("设置失败
(%$$#^66967*&%2)我型我塑www.5x54.com
,你没有输入任何值!");//检查输入是否为空
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
function getCookie(cookie_name) //自定义函数用于获取cookie的值
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
var allcookies = document.cookie; //声明一个变量allcookies
(%$$#^66967*&%2)我型我塑www.5x54.com
var value=null; //将value的初始值设为空
(%$$#^66967*&%2)我型我塑www.5x54.com
var searchs=cookie_name+"="; //给变量searchs赋cookie名
(%$$#^66967*&%2)我型我塑www.5x54.com
if(allcookies.length>0)//查看cookie是否为空
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
var offset=allcookies.indexOf(searchs); //找到要查找的变量名
(%$$#^66967*&%2)我型我塑www.5x54.com
if(offset!=-1) //判断所查找的变量名是否存在
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
offset+=searchs.length;
(%$$#^66967*&%2)我型我塑www.5x54.com
var end=allcookies.indexOf(";",offset); //找到变量值的结束位置
(%$$#^66967*&%2)我型我塑www.5x54.com
if(end==-1)//防止没加“;”号的情况发生
(%$$#^66967*&%2)我型我塑www.5x54.com
{
(%$$#^66967*&%2)我型我塑www.5x54.com
end=allcookies.length; //取得cookie的长度
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
value=unescape(allcookies.substring (offset,end));//取得变量的值
(%$$#^66967*&%2)我型我塑www.5x54.com
}else{
(%$$#^66967*&%2)我型我塑www.5x54.com
value=null; //将变量value赋为空
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
return value; //返回变量value的值
(%$$#^66967*&%2)我型我塑www.5x54.com
}
(%$$#^66967*&%2)我型我塑www.5x54.com
</script>
(%$$#^66967*&%2)我型我塑www.5x54.com
</head><!--文档头结束-->
(%$$#^66967*&%2)我型我塑www.5x54.com
<body> <!--文档体-->
(%$$#^66967*&%2)我型我塑www.5x54.com
<input type="submit" name="Submit" value="设置cookie值" onClick="setCookie();">
(%$$#^66967*&%2)我型我塑www.5x54.com
<input type="submit" name="Submit2" value="读取cookie值" onClick="alert (getCookie('username'))">
(%$$#^66967*&%2)我型我塑www.5x54.com
</body>
(%$$#^66967*&%2)我型我塑www.5x54.com
收藏此文章
打印
更新
编辑此文章
『关闭窗口』