0

I have a requirement, in jQuery, to show an alert if a cookie does not exist.

I cannot use the jQuery cookie plugin.

I've found a couple of scripts that I may be able to use, however, I cant seem to get them working in my jsfiddles. Can anyone assist me? Or are there other suggestions how to meet this requirement?

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."); 
 }
}    

Is there something I am doing wrong that the fiddles above are not creating alerts like I'm expecting?

4

2 回答 2

0

create a function that returns null or false if the cookie doesn't exist :

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

于 2013-06-07T12:46:40.160 回答
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;
}
于 2013-06-07T12:56:34.770 回答