doulongti5932 2014-01-18 19: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:

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 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线