duanfeng7756 2013-02-27 10:42
浏览 68

我们可以使用javascript检索和设置PHP cookie

I've set a cookie using PHP,

setcookie("redirect", $this->currentPage(), time() + 31536000);  

but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?

  • 写回答

4条回答 默认 最新

  • duanguanzai6181 2013-02-27 10:46
    关注

    Yes its possible.

    Try this to read cookie:

    function getCookie(c_name) {
        var i,x,y,ARRcookies=document.cookie.split(";");
        for (i=0;i<ARRcookies.length;i++) {
           x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
           y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
           x=x.replace(/^\s+|\s+$/g,"");
           if (x==c_name){
             return unescape(y);
           }
        }
     }
    
    // get cookie foo
    var foo = getCookie('foo');
    

    Try this to set a cookie:

    /**
     * Sets a cookie
     */
    function setCookie(c_name,value,exdays) {
        var exdate=new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
       document.cookie=c_name + "=" + c_value;
    }
    
    // set a cookie 'foo=bar' for 3 days
    setCookie('foo', 'bar', 3);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计