原生js cookie的使用例項setCookie()、getCookie()方法
阿新 • • 發佈:2018-12-30
01<html>
02<head>
03<title>原生js cookie的使用例項setCookie()、getCookie()方法</title>
04<scriptlanguage="javascript">
05<!--
06functionsetCookie(){
07 varnever=newDate();
08 //設定never的時間為當前時間加上十年的毫秒值
09 never.setTime(never.getTime()+10*365*24*60*60*1000);
10 varexpString="expires="+never.toGMTString ()+";";
11
12 document.cookie="area="+escape("北京海淀")+"; "+expString;
13 document.cookie="zipcode=100080;";
14
15}// end function
16
17
20functiongetCookie(name){
21 varresult=null;
22 //對cookie資訊進行相應的處理,方便搜尋
23 varmyCookie=""+document.cookie+";";
24 varsearchName="+name+"=";
25 var startOfCookie = myCookie.indexOf(searchName);
26 var endOfCookie;
27 if(satrtOfCookie != -1){
28 startOfcookie += searchName.length;
29 endOfCookie = myCookie.indexOf(";",startOfCookie);
30 result=(myCookie.substring(startOfCookie,endOfCookie));
31 }
32 returnresult;
33}//end function
34//-->
35</script>
36</head>
37 <body>
38<script>
39 document.write(document.cookie+"<br/>");
40 document.write("area is"+getCookie("area")+",and zipcode is"+getCookie("zipcode"));
41 document.write("<br/>");
42</script>
43</body>
44</html>
02<head>
03<title>原生js cookie的使用例項setCookie()、getCookie()方法</title>
04<scriptlanguage="javascript">
05<!--
06functionsetCookie(){
07 varnever=newDate();
08 //設定never的時間為當前時間加上十年的毫秒值
09 never.setTime(never.getTime()+10*365*24*60*60*1000);
10 varexpString="expires="+never.toGMTString
11
12 document.cookie="area="+escape("北京海淀")+"; "+expString;
13 document.cookie="zipcode=100080;";
14
15}// end function
16
17
20functiongetCookie(name){
21 varresult=null;
22 //對cookie資訊進行相應的處理,方便搜尋
23 varmyCookie=""+document.cookie+";";
24 varsearchName="+name+"=";
25 var startOfCookie = myCookie.indexOf(searchName);
26 var endOfCookie;
27 if(satrtOfCookie != -1){
28 startOfcookie += searchName.length;
29 endOfCookie = myCookie.indexOf(";",startOfCookie);
30 result=(myCookie.substring(startOfCookie,endOfCookie));
31 }
32 returnresult;
33}//end function
34//-->
35</script>
36</head>
37
38<script>
39 document.write(document.cookie+"<br/>");
40 document.write("area is"+getCookie("area")+",and zipcode is"+getCookie("zipcode"));
41 document.write("<br/>");
42</script>
43</body>
44</html>