js读取cookie方法总结
人气:0本文实例总结了js读取cookie方法。分享给大家供大家参考。具体实现方法如下:
一般关于js读取cookie方法有很多,我们下面的实例函数主要是利用split函数来分切,和document.cookie获取所有cookie再利用for遍历所有数组,判断如果cookie名相同,那么这个cookie 就是我们要找的。
方法一
复制代码 代码如下:
var acookie=document.cookie.split("; ");
function getck(sname)
{//获取单个cookies
for(var i=0;i<acookie.length;i++){
var arr=acookie[i].split("=");
if(sname==arr[0]){
if(arr.length>1)
return unescape(arr[1]);
else
return "";}}
return "";
}
function getck(sname)
{//获取单个cookies
for(var i=0;i<acookie.length;i++){
var arr=acookie[i].split("=");
if(sname==arr[0]){
if(arr.length>1)
return unescape(arr[1]);
else
return "";}}
return "";
}
方法二
复制代码 代码如下:
function getcookie(objname){//获取指定名称的cookie的值
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]);
}
}
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]);
}
}
方法三
复制代码 代码如下:
function getcookie(cookiename){
var cookiestring = document.cookie;
var start = cookiestring.indexof(cookiename + '= ');
if (start == -1) // 找不到
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));
}
var cookiestring = document.cookie;
var start = cookiestring.indexof(cookiename + '= ');
if (start == -1) // 找不到
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));
}
方法四
复制代码 代码如下:
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;
}
{
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;
}
希望本文所述对大家的javascript程序设计有所帮助。
加载全部内容