用cookie传递参数

实例:

Code
//1.html
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>
    
<title>1title>

    
<script type="text/javascript">
    
function setCookie(cookieName,cookieValue,nDays){
    
var today = new Date();
    
var expire = new Date();
    
if (nDays == null|| nDays == 0) nDays = 1;
    expire.setTime(today.getTime() 
+ 360000*24*nDays);
    document.cookie 
= cookieName + "=" + escape(cookieValue) + ";expire=" + expire.toGMTString();
    }

    
function login(){
    
var username = $("user").value;
    
var password = $("pass").value;
    
var save = $("save").checked;

    
if (username == "123" && password == "123"){
        
if (save) setCookie("username",username,7);
        
else setCookie("username",username,1);
        document.location 
= "2.html";
    }
    
else
        alert(
"error");
    }

    
function $(id){return document.getElementById(id);}
    
script>
head>

<body>
  
<div>用户名:<input type=text id=user>div>
  
<div>密码:<input type=text id=pass>div>
  
<div><input type=checkbox id=save>7天内无需登录
    
<input type=button value=login onclick=login()>div>
body>
html>
Code
//2.html
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>
    
<title>2title>
    
<script type="text/javascript">
    
function readCookie(cookieName){
        
var theCookie = "" + document.cookie;
        
var ind = theCookie.indexOf(cookieName);

        
if (ind == -1 || cookieName==""return "";

        
var indEnd = theCookie.indexOf(';',ind);
        
if (indEnd == -1) indEnd = theCookie.length;

        
return unescape(theCookie.substring(ind + cookieName.length + 1,indEnd));
    }

    
function $(id) {return document.getElementById(id);}

    
function init(){
        
var username = readCookie("username");
        
if (username && username.length > 0)
            $(
"msg").innerHTML = "

欢迎光临,"+username+"!

";
        
else
            $(
"msg").innerHTML = "请登录";
    }
    
script>
head>
<body onload=init()>
<div id=msg>div>
body>
html>

转载于:https://www.cnblogs.com/lolicon/archive/2009/01/19/1378407.html

你可能感兴趣的:(用cookie传递参数)