js如何设置cookie
1、首先说明一下我们是怎么做测试的,在AB两个页面中,我们在A页面写一个简单的登录界面,然后将登录信息写入cookie,然后在B页面读取cookie中的信息
2、建立两个html文件分别为A.html和B.html,注意后缀名称
3、在A.html里面写入的内容如下:
<body>
请输入用户名和密码:
<input id="userName" type="text" /> <input id="passwords" type="password" /><input type="button" onclick="login()" value="登录"/>
<script type="text/javaScript">
function login(){
// 获取用户名
var name = document.getElementById("userName");
// 获取密码
var pass = document.getElementById("passwords");
// 写入cookie
setCookie("userName", name.value);
setCookie("passwords", pass.value);
// 跳转到B页面
window.location.href="B.html";
}
function setCookie(name,value){
var Days = 30; //cookie 将被保存30天
var exp = new Date(); //获得当前时间
exp.setTime(exp.getTime() + Days*24*60*60*1000); //换成毫秒
document.cookie = name + "="+ value + ";expires=" + exp.toGMTString();
}
</script>
</body>
4、在B.html写入的内容如下:
<body>
获取到的用户名和密码为:
<label id="mylabel"></label>
<script type="text/javaScript">
var name = getCookie("userName");
var pass = getCookie("passwords");
var values = "userName=" + name + "; passwords=" + pass;
// 写入值到label标签
document.getElementById("mylabel").innerHTML = values;
// 从cookie中获取值的方法
function getCookie(name) {
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
</script>
</body>
5、到这里我们就已经写完测试案例了,接下来让我们来测试一下。
1、我们用打开A.html
2、在A.html内输入用户名:asdfqwer,密码:qwe123,然后点击登录按钮
3、可以看到结果完全符合我们的要求