Home > Article > Backend Development > How to get the value of cookie
Method 1:
let allcookies = document.cookie;function getCookie(cookie_name){ var allcookies = document.cookie; var cookie_pos = allcookies.indexOf(cookie_name); //索引的长度 // 如果找到了索引,就代表cookie存在, // 反之,就说明不存在。 if (cookie_pos != -1) { // 把cookie_pos放在值的开始,只要给值加1即可。 cookie_pos += cookie_name.length + 1; //这里容易出问题,所以请大家参考的时候自己好好研究一下 var cookie_end = allcookies.indexOf(";", cookie_pos); if (cookie_end == -1) { cookie_end = allcookies.length; } var value = unescape(allcookies.substring(cookie_pos, cookie_end)); //这里就可以得到你想要的cookie的值了。。。 } return value; }// 调用函数let cookie_val = getCookie(cookie的名字);
Method 2
function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; }// 调用函数let cookie_val = getCookie(cookie的名字);
Principle:
(1) Get all cookie values through document.cookie, Get a string containing all values of a cookie.
(2) Because all cookies are separated by semicolons, use split(‘;’) to split the string into an array and save it.
(3) Determine whether each item in the array contains the cookie name. If so, just take out the corresponding value.
The above is the detailed content of How to get the value of cookie. For more information, please follow other related articles on the PHP Chinese website!