JavaScript的cookie操作

📅 2019-12-25 👤 超级管理员
#技术文章 #建站教程 #教程 #JavaScript
🤖 AI摘要

文章详细介绍了JavaScript中Cookie的四种操作函数。setCookie函数通过设置名称、值及过期天数创建Cookie,getCookie函数通过解码和遍历数组获取指定值,checkCookie函数检查是否存在用户名Cookie,存在则显示问候否则提示输入并保存,deleteCookie函数通过设置过期时间为1970年实现删除。核心内容涵盖Cookie的创建、读取、检测与清除完整流程,代码示例展示了实现细节和常见问题处理。

//设置cookie函数
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
} 
//设置cookie函数

上面这个函数的的参数是:cookie 的名字(cname),cookie 的值(cvalue),以及知道 cookie 过期的天数(exdays)。
通过把 cookie 名称、cookie 值和过期字符串相加,该函数就设置了 cookie。

//获取cookie函数
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
         }
     }
    return "";
} 
//获取cookie函数

把 cookie 作为参数(cname)。
创建变量(name)与要搜索的文本(CNAME”=”)。
解码 cookie 字符串,处理带有特殊字符的 cookie,例如 “$”。
用分号把 document.cookie 拆分到名为 ca(decodedCookie.split(';'))的数组中。
遍历 ca 数组(i = 0; i < ca.length; i++),然后读出每个值 c = ca[i]。
如果找到 cookie(c.indexOf(name) == 0),则返回该 cookie 的值(c.substring(name.length, c.length)。
如果未找到 cookie,则返回 ""。

创建检查 cookie 是否设置的函数。
如果已设置 cookie,将显示一个问候。
如果未设置 cookie,会显示一个提示框,询问用户的名字,并存储用户名 cookie 365 天,通过调用 setCookie 函数:

function checkCookie() {
    var username = getCookie("username");
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }
} 

删除cookie

document.cookie = "cname=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";


← 返回首页 最后更新: 2025-11-11

您正在浏览AMP加速版本,评论功能在完整版中可用。

查看完整版本