Javascript中的Cookie操作

时间:2024-01-01 15:51:51
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
//添加cookie
function setCookie(key, value, delay) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + delay);//设置过期时间
document.cookie = key + "=" + value + ";expires=" + oDate;
} setCookie("name", "hahah", 13);
setCookie("pwd", "sdfsf", 234);
//删除cookie
function removeCookie(key){
setCookie(key,1,-1);
}
</script>
</head>
<body>
</body>
</html>

  //本域内设置cookie

<script type="text/javascript">
function setCookie(c_name,value,expiredays) {
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/;domain=b.com";
}
window.onload=function(){
setCookie("listallwjh","sfwjh");
alert("Cookie设置成功!");
}
</script>

  跨域设置cookie

<script>
function getCookie(c_name) {
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1 ;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
window.onload=function(){
var c_name="listallwjh";
if(getCookie("listallwjh")!=null){
alert(getCookie("listallwjh"));
}
}
</script>

  //读取Cookie

 //读取cookie
function getCookie(key) {
var arr = document.cookie.split(";");
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split("=");
if (arr2[0]==key) {
return arr2[1];
}
}
}