remove Cookie using jquery not working

2020-06-08 05:19发布

I have two cookies in my JS file and I want to remove them.

I have tried the code below but it is not working

 $.removeCookie('filter', { path: '/Home/' });
 $.removeCookie('Pfilter', { path: '/Home/' });

I have also tried the below for null cookies, but this is also not working.

Thanks for the help

$.cookie('filter',null, { path: '/Home/' });

6条回答
虎瘦雄心在
2楼-- · 2020-06-08 05:50

Did you try $.cookie("name", null);

$.removeCookie('filter', { path: '/' });
查看更多
smile是对你的礼貌
3楼-- · 2020-06-08 05:52

I was having the same issue with jquery version 1.7.1 and jquery cookie version 1.4.1

This was driving me crazy so I decided to dive into the source code and I figured out what is wrong.

Here is the definition of $.removeCookie

$.removeCookie = function (key, options) {
    if ($.cookie(key) === undefined) { // this line is the problem
        return false;
    }

    // Must not alter options, thus extending a fresh object...
    $.cookie(key, '', $.extend({}, options, { expires: -1 }));
    return !$.cookie(key);
};

As you can see when the function checks if the cookie exists it doesn't take the options object into account. So if you are on a different path than the cookie you're trying to remove the function will fail.

A Few Solutions:

Upgrade Jquery Cookies. The most recent version doesn't even do that sanity check.

or add this to you document ready

$.removeCookie = function (key, options) {
    if ($.cookie(key, options) === undefined) { // this line is the fix
        return false;
    }

    // Must not alter options, thus extending a fresh object...
    $.cookie(key, '', $.extend({}, options, { expires: -1 }));
    return !$.cookie(key);
};

or when removing cookies do something like this:

$.cookie('cookie-name', '', { path: '/my/path', expires:-1 });
查看更多
ら.Afraid
4楼-- · 2020-06-08 05:58

If you use a domain parameter when creating a cookie, this will work

$.removeCookie('cookie', { path: '/' , domain  : 'yourdomain.com'});
查看更多
欢心
5楼-- · 2020-06-08 06:09

What works for me is setting the cookie to null before removing it: $.cookie("filter", null); $.removeCookie("filter);

查看更多
祖国的老花朵
6楼-- · 2020-06-08 06:11

It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

enter image description here

You might be using the generic / for your path instead of /Home/. Give the code below a try.

To delete a cookie with jQuery set the value to null:

$.removeCookie('filter', { path: '/' });
查看更多
家丑人穷心不美
7楼-- · 2020-06-08 06:12

This simple way it works fine:

$.cookie("cookieName", "", { expires: -1 });
查看更多
登录 后发表回答