最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to use cookies in JQuery - Stack Overflow

programmeradmin7浏览0评论

It is easy to use cookies in serverside like PHP,.NET...etc

I would like to use cookies for static website which is just HTML, CSS & JQuery .

Anybody know how to implement cookies in JQuery ?

It is easy to use cookies in serverside like PHP,.NET...etc

I would like to use cookies for static website which is just HTML, CSS & JQuery .

Anybody know how to implement cookies in JQuery ?

Share Improve this question asked Mar 15, 2012 at 13:00 Mo.Mo. 27.5k36 gold badges166 silver badges232 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 6

the jQuery Cookie plugin is one way to go:

https://github./carhartl/jquery-cookie

You use it like so:

$.cookie('cookie_name', 'value'); // to set

$.cookie('cookie_name'); // to get

You can use this plugin

example: to set a cookie

$.cookie("example", "foo");

You don't need a jQuery plugin, you can easily access cookies in JavaScript. Here's how: https://developer.mozilla/en/DOM/document.cookie

But maybe the plugins linked in the other answers will give you easier access.

Are you sure that cookie is exactly what you need? There are localStorage which is much better in many scenarios.

You wrote that you want use cookies with static website, but cookies will be sent to the server and returned back. Is it really needed that you sent the information to the server on leading the static website? It increases the size of HTTP header and decreases the performance of the web site (see here for example).

Cookies have very hard restrictions. Corresponds to the section 6.3 of rfc2109 or 6.1 of rfc6265: At least 4096 bytes per cookie, at least 50 cookies per domain (20 in rfc2109), at least 3000 cookies total (300 in rfc2109). So the cookies one can't use to save too many information. For example if you would save state of every grid of every your web page you can quickly achieve the limits.

If you just want to save some users preferences for the page you can use localStorage and the usage is really easy.

If you prefer to use some jQuery plugin instead of direct usage of localStorage and if you need support old web browsers (like IE6/IE7) then you can use jStorage for example. In the case you has only less size of storage: 128 KB instead of 5 MB (see here and IE userData Behavior), but it's better as 4K which one has for cookies (see here).

I want that you just think a little about alternatives to cookies.

Read Cookie:

var cookieValue = $.cookie("cookieName");

Write Cookie:

$.cookie("cookieName", "CookieValue");

You can use plain JS by accessing document.cookie.

See: http://jsfiddle/ShsYp/

Also: https://developer.mozilla/en/DOM/document.cookie

A simple, lightweight jQuery plugin for reading, writing and deleting cookies.For details demo and example see a link.
https://github./carhartl/jquery-cookie

发布评论

评论列表(0)

  1. 暂无评论