Home  >  Article  >  Backend Development  >  How to get the value of cookie

How to get the value of cookie

清浅
清浅Original
2019-05-05 17:24:1066606browse

How to get the cookie value: First get all the cookie values ​​through [document.cookie]; then because you get a string with all the values ​​together, you can use the split function to split the string into an array; Finally, determine whether there is a cookie name in the array, and if so, just take it out.

How to get the value of cookie

The following are two ways to get the value in the 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(&#39;;&#39;);  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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what is phpnowNext article:what is phpnow