如何在javascript中从cookie中获取值

如何在javascript中从cookie中获取值,javascript,cookies,Javascript,Cookies,我需要的是: 我需要使用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; e

我需要的是:

  • 我需要使用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的事件\u 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')); 
  • im面临的问题im无法从cookie中获取用户和事件id
  • im使用symphony框架,需要在twig文件中实现

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

我建议您仔细阅读cookies:

下面的代码来自那篇文章

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
函数readCookie(名称){
变量nameEQ=name+“=”;
var ca=document.cookie.split(“;”);
对于(变量i=0;i