在javascript中将cookie值解析为if / else

时间:2012-09-22 18:10:47

标签: javascript cookies session-cookies if-statement

所以我有一个简单的会话cookie检索器,并将cookie值写入页面。只有两个值,“是”和“否”,否则返回null。目前,它会检查是否有值,如果有,则将该值写入页面。我如何告诉脚本有条件地写入值(即写入“是”,因为值为“是”,“否”是相同的,而不是仅仅传递响应)而不是它是否存在?

<script>
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};
</script>

...

<p>
Response 1: 
<script>
var res1 = readCookie('res1')
if (res1) {
    document.write('res1')
}
else {
document.write("You did not respond.")
};
</script>
</p>

1 个答案:

答案 0 :(得分:0)

function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ))
    return matches ? decodeURIComponent(matches[1]) : undefined
}

document.write(getCookie('res1') != undefined ? 'res1' : 'You did not respond.')