html结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cookies</title>
</head>
<body onload="checkCookie()"> </body>
</html>
定义了三个函数:设置cookis,检查cookie以及触发函数
// 我们会创建一个可在 cookie变量中存储访问者姓名的函数
function setCookies(name,value){
var expdate = new Date();
expdate.setTime(expdate.getTime() + **);
console.log(expdate);
document.cookie = name+"="+value+";expire="+expdate.toUTCString()+";path=/"; } // 创建另一个函数来检查是否已设置 cookie:
function getCookies(c_name){
if(document.cookie.length>){
var c_start = document.cookie.indexOf(c_name+'=');
if(c_start != -){
c_start = c_start + c_name.length + ;
var c_end = document.cookie.indexOf(";",c_start)
if(c_end == -){
c_end = document.cookie.length;
} return unescape(document.cookie.substring(c_start,c_end))
}
}
return "";
} // 检测 cookis
function checkCookie(){
var username = getCookies('username');
if(username!=null && username!=""){
alert("Welcome again "+ username+" !");
}else{
username = prompt('Please enter your name:',"");
if(username!=null && username!=""){
setCookies('username',username)
}
}
}
完成!但是你会发现在你的浏览器内没有看到效果???
这是怎么回事呢,我们需要一个服务环境,为了方便我搭建了一个简单的node环境
http.js
var http = require('http');
var fs = require('fs'); var querystring = require('querystring'); // 侦听服务器的request事件
http.createServer(function(req,res){ var urlIndex = req.url.substring();
if(req.url == '/favicon.ico'){
res.end();
}else{
hetTemplate(res,urlIndex);
} }).listen(,function(){console.log('run!')}); function hetTemplate(res,urlIndex){
fs.readFile('./'+urlIndex+'.html',function(err,data){
if(err) {
return hadError(err,res);
}else{
res.end(data)
}
})
}
function hadError(err,res){
console.log(err);
res.end('Server error');
}
ok!现在我们可以尽情的测试了!
访问方式:locahost:2016/文件名称
http文件和你的html文件在同一目录下,当然你科一不这样做,改一下源码吧