如何从JavaScript中的Cookie捕获部分数据

时间:2019-01-22 14:14:35

标签: javascript cookies

我在登录网页时有一个cookie。这是Cookie的详细信息

"{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}" 

我需要在变量中捕获XXVCode,如何在此网页上的javascript中做到这一点?

2 个答案:

答案 0 :(得分:1)

方法1:

您可以使用getCookie()函数:

// Code collected from w3schools.com

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  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 "";
}

然后您可以致电:

getCookie('XXVCode');

方法2:

注意:您的cookie字符串用double quote包裹,应该用single quote包裹。 因为double quote中的double quote将显示syntax error

var cookie = '{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}';

var cookieArray = JSON.parse(cookie)

const XXVCode = cookieArray['XXVCode'];

答案 1 :(得分:0)

转换为对象,然后访问密钥

const cookie = "{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"

const cookieJSON = JSON.parse(cookie)

const XXVCode = cookieJSON['XXVCode']