获取cookie信息但没有任何作用

时间:2017-02-16 15:13:27

标签: javascript jquery

// Set COOKIE
$cookie_name = 'domain[user]';
$cookie_value = 'domain[id]';

// Cookie need to change right away after user press login
setcookie($cookie_name,$sub_name,time()+(60*60*24),'/');
setcookie($cookie_value,$auth_id,time()+(60*60*24),'/');

// Forced cookie to exit after set
$_COOKIE['domain']['user'] = $sub_name;
$_COOKIE['domain']['id'] = $auth_id;

我在php上设置我的域名,但是我想通过JavaScript或jquery获取它,但是我遇到了问题。

这是我尝试过的。

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;
}

var value = readCookie('domain["user"]');

alert(value); 

如何获取我的Cookie信息?

1 个答案:

答案 0 :(得分:0)

在解析之前你必须解码它。

试试这个:

function readCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    //var decodedCookie = "fbm_229931260731834=base_domain=.chris01.com; fblo_229931260731834=y; PHPSESSID=f1djg4brueiqkkqnkjiqj6s5q0; domain[user]=admin; domain[authID]=ba981df7c9aa72ad461461ad524cca01049938f8869098b31065058e7fdaa7e65e3072f637d43c10ba51a5cd6f5ec77d0ccf4befc066320c686168d7638b57e3";
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var value = readCookie("domain[user]");

alert(value); 

请注意不要像这样调用cookie名称:readCookie('domain["user"]');

你必须这样称呼:readCookie("domain[user]");