我在登录网页时有一个cookie。这是Cookie的详细信息
"{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
我需要在变量中捕获XXVCode,如何在此网页上的javascript中做到这一点?
答案 0 :(得分: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');
注意:您的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']