繁体   English   中英

如何在JavaScript中从Cookie中获取价值

[英]how to get value from cookie in javascript

我需要的:

  • 我需要使用cookie中的用户和evnt_id。

     document.cookie 

    字串:

     " country=India; countryCode=IN; __gads=ID=369fde524de77341:T=1417077062:S=ALNI_MakhfG3fYeRIwt9Uw4xSUE8m-2hHw; fbm_172404889604820=base_domain=.10times.com; PHPSESSID=4e467l46efdmvc9vktknod85b2; evnt_id=9; industry=74; evnt_name=India International Trade Fair; evnt_url=iitf; km_ai=jE0JIU3hamljHh0DrWRC%2FR50QNI%3D; km_lv=x; __zlcmid=SAeGECzmK8Nrve; user_flag=2; user=13530767; _ga=GA1.2.1767513107.1417003918; linkedin_oauth_ro57ogahnixy_crc=null; km_uq=; kvcd=1418207265523; _ga=GA1.3.342868374.1416999745; id=13530767; email=afeef1915%40yahoo.com; name=Mohd+Afeef; image_flag=http%3A%2F%2Fgraph.facebook.com%2F100001729894039%2Fpicture". 
  • 我需要拿

    • 用户。
    • 来自cookie的event_id。

我尝试过的代码:

function setCookie(key, value) {  
var expires = new Date();  
expires.setTime(expires.getTime() + 31536000000); //1 year  
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();

}  

   function getCookie(key) {  
     var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');

     return keyValue ? keyValue[2] : null;  
       }  

    setCookie('evnt_id','evnt_id');  
   alert(getCookie('evnt_id')); 
  • 我面临的问题是我无法从cookie中获取用户和event_id。
  • 即时通讯使用交响框架,需要在树枝文件中实现。

这个问题以前已经解决过。 不要重新发明轮子:)

我建议您阅读Cookie: http//www.quirksmode.org/js/cookies.html

下面的代码来自该文章。

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

console.log(readCookie('evnt_id'));  //9
console.log(readCookie('user'));     //13530767

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM