开发者

Create, read, and erase cookies with jQuery [duplicate]

This question already has answers here: How do I set/unset a cookie with jQuery? (18 answers) Closed 2 years ago.

Somebody help me. How to creat开发者_开发问答e, read and erase some cookies with jQuery ?


Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.


As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
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);
}

You can access like below,

createCookie("test","test",1); // to create new cookie

readCookie("test"); // to retrive data from cookie

eraseCookie("test"); // will delete that cookie


Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie


Google is my friend and it showed me this page:

  • http://www.electrictoolbox.com/jquery-cookies/
  • How do I set/unset cookie with jQuery?
  • Can jQuery read/write cookies to a browser?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜