js如何设置cookie

2025-10-22 00:06:47

1、首先说明一下我们是怎么做测试的,在AB两个页面中,我们在A页面写一个简单的登录界面,然后将登录信息写入cookie,然后在B页面读取cookie中的信息

2、建立两个html文件分别为A.html和B.html,注意后缀名称

js如何设置cookie

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>

js如何设置cookie

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>

js如何设置cookie

5、到这里我们就已经写完测试案例了,接下来让我们来测试一下。

1、我们用打开A.html

js如何设置cookie

2、在A.html内输入用户名:asdfqwer,密码:qwe123,然后点击登录按钮

js如何设置cookie

3、可以看到结果完全符合我们的要求

js如何设置cookie

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢