如何从javascript中获取cookie的价值

时间:2014-12-10 11:33:31

标签: javascript cookies

我需要什么:

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

    document.cookie
    

    string:

    " 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。
  • 即时通讯使用symphony框架,需要在twig文件中实现。

1 个答案:

答案 0 :(得分:0)

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

我建议你阅读cookies: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