doulongti5932 2014-01-18 11:43
浏览 69
已采纳

如何检测是否在Javascript中设置了cookie?

I have set a session in PHP, which is creating a cookie: PHPSESSID... I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.

In PHP I am setting the sessions like:

  1. session_start();
  2. $_SESSION['source'] = &$ref['source'];
  3. $_SESSION['term'] = &$ref['term'];
  4. session_write_close();

I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?

At the moment I am just using:

document.cookie.indexOf( 'PHPSESSID' )

which seems like a bit of a botch.

  • 写回答

2条回答 默认 最新

  • dpd3447 2014-01-18 12:14
    关注

    The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.

    You could parse the cookies with the following function (not tested):

    function getCookieValue(name)
    {
        // find cookie entry in middle?
        var s=document.cookie,
            c=s.indexOf("; "+name+"=");
    
        if(c==-1)
        {
            // no, is it at the start?
            c=s.indexOf(name+"=");
            if(c!=0) return null;
        }
    
        // get length of value
        var l=c+name.length+1,
            e=s.indexOf(";",l);
    
        // is it at the end?
        if(e==-1) e-s.length;
    
        // cut out the value
        return s.substring(l,e);
    }
    

    Hope this helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部