如何在 JavaScript 中从 cookie 中捕获部分数据



我在登录网页时有一个cookie。这是饼干的细节

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

我需要在一个变量中捕获XXVCode,我怎么能在这个网页上的javascript中做到这一点?

方法 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'];

转换为对象,然后访问键

const cookie = "{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
const cookieJSON = JSON.parse(cookie)
const XXVCode = cookieJSON['XXVCode']

最新更新