如何在没有JQuery的情况下在JavaScript中创建cookie?

时间:2015-02-22 04:33:15

标签: javascript jquery cookies

所以我说的是你可以在不使用JQuery而只使用JavaScript的情况下创建一个cookie 你有答案吗?

2 个答案:

答案 0 :(得分:4)

我有这些简单的功能

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

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;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

现在,调用函数

createCookie('ppkcookie','testcookie',7);

var x = readCookie('ppkcookie')

答案 1 :(得分:0)

Create cookies with javascript

JavaScript可以使用document.cookie属性创建,读取和删除cookie。

使用JavaScript,可以像这样创建一个cookie:

document.cookie = "username=John Doe";

您还可以添加到期日期(以UTC时间为单位)。默认情况下,在浏览器关闭时删除cookie:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

使用path参数,您可以告诉浏览器cookie属于哪个路径。默认情况下,cookie属于当前页面。

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

所有代码:

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;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

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