js cookie使用方法以及跨域访问

cookie 是存储于访问者的计算机中的变量,常用属性包含五类:Name,Value,Domain,Path ,Expires ;

Name(名称):存储的key名。

Value(值):存储的value值。

Domain (域):指定关联的WEB服务器或域,比如 baidu.com。

Path(路径):指定与cookie关联的WEB页。

Expires(过期时间):指定cookie的生命期,具体是值是过期日期。

设置cookie:

setCookie('key1','你好');
1 function setCookie(c_name,value,expiredays) {
2     var exdate=new Date();
3     exdate.setDate(exdate.getDate()+expiredays);
4     document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ";path=/;domain=" + document.domain;
5 }

获取cookie:

getCookie(key1);
 1 function getCookie(c_name){
 2     if (document.cookie.length>0){
 3         var c_start = document.cookie.indexOf(c_name + "=");
 4         if (c_start!=-1){
 5             c_start = c_start + c_name.length+1;
 6             var c_end=document.cookie.indexOf(";",c_start);
 7             if (c_end==-1){
 8                 c_end=document.cookie.length;
 9             }
10             return unescape(document.cookie.substring(c_start,c_end));  
11         }   
12     }  
13     return "";  
14 }
原文地址:https://www.cnblogs.com/front-boy/p/9377563.html