精通脚本黑客学习笔记(四)

4.5.2 cookies组成

KV对,一个cookies最多只能存储20个。

Set-cookie:name=value;[expires=date];[path=pathname];[domain=domainname];[secure];

name是数据项的名称,value是数据项的值。

cookie是document对象的一个属性

document.cookie=" id="";expires="";path="" ";


encodeURI(uri)    使用URI编码

decodeURI(uri)    解码URI编码

######################################################

<center>
<h2>URL编码解码</h2>
<script language="javascript">
function urlEncoding(form){
   var myString=form.input.value;
   alert(encodeURI(myString));
   }
function urlDecoding(form){
   var myString=form.input.value;
   alert(decodeURI(myString));
   }
</script>
</head>
<body bgcolor="#666666">
请输入要编码或解码的字符串:<p>
<form name="form1">
<input type="text" name="input" size=40><p>
<input type="button" name="button1" value="查看编码结果"
onclick="urlEncoding(this.form);"><p>
<input type="button" name="button2" value="查看解码结果"
onclick="urlDecoding(this.form);"><p>
</form>

######################################################################

<title>创建cookies</title>
<center>
<h2>创建cookies演示</h2>
<script language="javascript">
function makeCookie(form){
   var when=new Date();
   when.setTime(when.getTime()+24*60*60*1000);
   when.setFullYear(when.getFullYear()+1);
   yname=form.yourname.value;
   ypasswd=form.yourpasswd.value;
   document.cookie=encodeURI("name")+"="+encodeURI(yname)+";expires="+when.toGMTString();
   document.cookie=encodeURI("passwd")+"="+encodeURI(ypasswd)+";expires="+when.toGMTString();
   alert(document.cookie);
   }
function welcome(myForm){
   you=myForm.yourname.value;
   var position=document.cookie.indexOf("name=");
   if(position != -1){
       var begin=position+5;
       var end=document.cookie.indexOf(";",begin);
       if(end == -1){end=document.cookie.length;}
       you=decodeURI(document.cookie.substring(begin,end));
       str=you;
       alert("欢迎你!"+you);
       }
   else{alert("嘿嘿,还没有cookie.");}
   }
</script>
</head>

<body bgcolor="#999999" onLoad="document.form1.reset()">
<h3>用户登录</h3>
<form name="form1">
用户名:
<input type="text" name="yourname"><p>
密  码:
<input type="password" name="yourpasswd"><p>
<input type="button" value="创建cookie" onclick="makeCookie(this.form)"><p>
<input type="button" value="查看cookie" onclick="welcome(this.form)"><p>
</form>
</body>


你可能感兴趣的:(JavaScript,cookie)