开发者

How do you setup a cookie which expires after 5mins in jquery?

开发者 https://www.devze.com 2023-04-10 05:36 出处:网络
I am unsure on how to setup a cookie on the following code : http://jsfiddle.net/zidski/GmLVj/8/ I want it to show for 5mins when logged in and then if I press on log out it would destroy the cookie.

I am unsure on how to setup a cookie on the following code : http://jsfiddle.net/zidski/GmLVj/8/

I want it to show for 5mins when logged in and then if I press on log out it would destroy the cookie.

Can anyone help??开发者_C百科


For 5 mins you need to modify it to : -

var date = new Date();
date.setTime(date.getTime() + (5 * 60 * 1000));
$.cookie("example", "foo", { expires: date });

You have set it to 30 minutes now.


You don't really need jquery for this (see this article for a tutorial).

Anyway there's a plugin called jQuery Cookie, which can help you with this.

To create a cookie with a lifetime of 5 minutes:

var expires = new Date();
expires.setMinutes( expires.getMinutes() + 5 ); // Create a date 5 minutes from now

// The path parameter is needed to make this cookie valid across the whole page
$.cookie('login_id', 'cafed00d', {expires: expires, path: '/'});

To destroy said cookie:

$.cookie('login_id', null);

Note that if this is a secure login, you should have server-side checks in place, because users can inspect your JavaScript and modify cookies at will.


You should use jQuery cookie plugin. The plugin allows you to set an expiry date like this:

{expires: date}

where date is a date object. In your case you should do (for 5 minutes):

var date = new Date();
date.setTime(date.getTime() + (5 * 60 * 1000));


5 minutes is 5 * 60 * 1000 miliseconds.

var date = new Date();
 var minutes = 5;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });
0

精彩评论

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