[英]how to capture part of data from cookie in javascript
我在登錄網頁時有一個cookie。 這是Cookie的詳細信息
"{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
我需要在變量中捕獲XXVCode,如何在此網頁上的javascript中執行此操作?
您可以使用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'];
轉換為對象,然后訪問密鑰
const cookie = "{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
const cookieJSON = JSON.parse(cookie)
const XXVCode = cookieJSON['XXVCode']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.