检查cookie是否存在不使用jQuery cookie插件

时间:2013-06-07 12:41:55

标签: jquery cookies

我在jQuery中要求在cookie不存在时显示警告。

我无法使用jQuery cookie插件。

我发现了一些我可以使用的脚本,但是,我似乎无法让它们在我的jsfiddles中工作。任何人都可以帮我吗?或者是否有其他建议如何满足此要求?

http://jsfiddle.net/JustJill54/a3tgP/2/

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

$(document).ready(function(){ 
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
        alert("Cookie not found.");
    }
    else {
        // do cookie exists stuff
        alert("MyCookie");
    }
}

http://jsfiddle.net/JustJill54/hYvX3/1/

$(document).ready(function(){ 
var acookie = ReadCookie("cookiename");
if(acookie.length == 0)
 { 
    alert("Cookie not found."); 
 }
}    

上面的小提琴有没有像我期待的那样创造警告?

2 个答案:

答案 0 :(得分:0)

如果cookie不存在,则创建一个返回null或false的函数:

function getCookie(c_name) {
    var c_value = document.cookie,
        c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) c_start = c_value.indexOf(c_name + "=");
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}

var acookie = getCookie("cookiename");
if (!acookie) {
    alert("Cookie not found.");
}

FIDDLE

答案 1 :(得分:0)

function getCookie(name) {  
    var a = name + "=";  
    var al = a.length;  
    var cl = document.cookie.length;  
    var i = 0;  
    while (i < cl) {    
        var j = i + al;    
        if (document.cookie.substring(i, j) == a)    
        {
            var endstr = document.cookie.indexOf (";", j);  
            if (endstr == -1)    
                endstr = document.cookie.length;  
            return unescape(document.cookie.substring(j, endstr));
        }       
        i = document.cookie.indexOf(" ", i) + 1;    
        if (i == 0) break;   
    }  
    return null;
}