Home  >  Article  >  Web Front-end  >  Summary of js reading cookie methods_javascript skills

Summary of js reading cookie methods_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:32:441385browse

The example in this article summarizes the js reading cookie method. Share it with everyone for your reference. The specific implementation method is as follows:

Generally, there are many ways to read cookies in js. Our example function below mainly uses the split function to split, obtain all cookies with document.cookie, and then use for to traverse all arrays to determine if the cookie names are the same, then this cookie That's what we're looking for.

Method 1

Copy code The code is as follows:
var acookie=document.cookie.split("; ");
function getck(sname)
{//Get individual cookies
for(var i=0;i var arr=acookie[i].split("=");
if(sname==arr[0]){
if(arr.length>1)
return unescape(arr[1]);
else
return "";}}
return "";
}

Method 2

Copy code The code is as follows:
function getcookie(objname){//Get the value of the cookie with the specified name
var arrstr = document.cookie.split("; ");
for(var i = 0;i < arrstr.length;i ){
var temp = arrstr[i].split("=");
if(temp[0] == objname) return unescape(temp[1]);
}
}

Method 3
Copy code The code is as follows:
function getcookie(cookiename){
var cookiestring = document.cookie;
var start = cookiestring.indexof(cookiename '= ');
if (start == -1) // Not found
return null;
start = cookiename.length 1;
var end = cookiestring.indexof( "; ", start);
if (end == -1) return unescape(cookiestring.substring(start));
return unescape(cookiestring.substring(start, end));
}

Method 4

Copy code The code is as follows:
function readcookie(name)
{
var cookievalue = "";
var search = name "=";
if(document.cookie.length > 0)
{ 
Offset = document.cookie.indexof(search);
If (offset != -1)
{                                Offset = search.length;
End = document.cookie.indexof(";", offset);
If (end == -1) end = document.cookie.length;
Cookievalue = unescape(document.cookie.substring(offset, end))
}  
}  
Return cookievalue;
}
I hope this article will be helpful to everyone’s JavaScript programming design.

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