doulongti5932 2014-01-18 19:43
浏览 68
已采纳

如何检测是否在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:

session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
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 20: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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题