Home
Working with the cookie using Jquery
A few days ago decided to investigate in detail with cookies: how they work, the structure of how to use. To understand the final decision was made to download the plugin to work with cookies on Jquery. Can credit for plug-in included Cookie Plugin for jQuery.
I'll start with perhaps the theory. Cookies are part of HTTP. From server to client cookie sent in the header of HTTP-server response. More precisely - in the field of the Set-Cookie header. Field Set-Cookie can contain data from several cookies. Also in the HTTP-response header can contain multiple fields Set-Cookie. Field Format Set-Cookie header HTTP-server response is given below:
Set-Cookie: <name>=<value>[; <name>=<value>]... [; expires=<date>][; domain=<domain_name>] [; path=<some_path>][; secure][; httponly]
We see that the line Set-Cookie response header Server consists of a sequence of substrings separated by ";" (semicolon). At first, followed by one or more pairs of <name> = <value>. Each of these pairs corresponds to a single cookie with the given name and value value. Then follow the attributes that set the cookie contained in this field Set-Cookie. Next is a description of the attribute values cookie.
- Attribute expires. Specified in the format: expires =. The date and time set by the end of a given field Set-Cookie header HTTP-server response cookie. Value should be a string that specifies the time in Greenwich (GMT) in the format "DAY, DD-MMM-YYYY HH: MM: SS GMT" (eg "Tue, 28 Feb 2006 12:41:04 GMT"). After the expiration of the cookie are deleted by your browser. If the attribute is not specified expires (the time the cookie is not set), cookie deleted at the end of the browser. This cookie is called "in-session" (only until the end of the current session).
- Attribute domain. Specified in the format domain =. Defines the end of the set of domain names, which really sets the cookie. For example, if you install cookie, the value well. codeguru.ru, set cookie will be sent to the server when you request documents from sites located on domains web.codeguru.ru, forum.codeguru.ru, etc. In this additional condition will be sending cookie attribute value assertion path - see below. Attribute domain is very useful. It can be used, for example, to organize a unified system of user authentication for various web-services, located in different subdomains. For example, on the main site and forum site. To avoid uncontrolled send cookie, the value should not only contain the name of the zone (eg,. com,. net.ru, etc.).
- Attribute path. Specified in the format path =. Defines a set of URL, which really sets the cookie. For example, if when you install the same cookie / temp, then set cookie will be sent when requesting documents, including the path / temp000 and / temp / temp.htm. If the path value is not specified, it is accepted as a path to a resource, when asked which provided a cookie.
- Attribute secure. This attribute is a Boolean. Specifying the attribute in the field of secure Set-Cookie header HTTP-server response does set cookie secure. This cookie will be sent to the server only via https. HTTPS - it's practically the same protocol as http, only the data between the client and the server are transmitted over a secure (encrypted data) SSL (Secure Socket Layer) connection.
- Attribute HttpOnly. This attribute is a Boolean. Specifying the attribute in the HttpOnly Set-Cookie header HTTP-server response does not set cookie available to client script (this applies for security reasons).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
jQuery.cookie = function(){ var url = location.href; // путь для устанавливаемых кук this.cookieID = "cookie"; // имя для переменной, которая будет содержать наши куки this.set = function(options){ // Функция для установки кук var cookieContent = ''; // инициализируем переменную для цикла for var filterProperties = {"cookieID":0,"set":1,"get":2}; // создаем объект с известными значениями options = options || {}; // если переданы пользовательские переменные, используем их. По умолчанию ничего не устанавливаем for(var property in this){ // перебираем все элементы полученного объекта if(!(property in filterProperties)){ // вытягиваем все элементы кроме тех, которые содержатся в filterProperties if (this[property] === null) this[property] = ''; // если имеем ноль заменяем на '' cookieContent += (property) + ':' + (this[property]) + ','; // записываем имя переменной + значение переменной } } cookieContent = cookieContent.substring(0,cookieContent.length-1); // удаляем последнюю запятую var expires = ''; // инициализируем переменную if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { // если у нас есть какое ли значение то var date; // создаем переменную для даты if (typeof options.expires == 'number') { // если это число date = new Date(); // текущую дату date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); // устанавливаем время } else { date = options.expires; // пустое значение; куки будут храниться до конца сессии } expires='; expires='+ date.toUTCString(); // устанавливаем время жизни кук } var path = options.path ? '; path=' + (options.path) : ''; // устанавливаем url для которых действительны устанавливаемые куки var domain = options.domain ? '; domain=' + (options.domain) : ''; // устанавливаем мия сайта var secure = options.secure ? '; secure' : ''; // указываем, следует ли шифровать данные или нет document.cookie = [this.cookieID, '=',encodeURIComponent(cookieContent), expires, path, domain, secure].join(''); // делаем из массива строку и записываем ее в куки return true; }; this.get = function(){ // функция для получения кук var cookieValue = ''; if (document.cookie && document.cookie != '') { // если куки доступны и существуют var cookies = document.cookie.split(';'); // разбили и получили массив for (var i = 0; i < cookies.length; i++) { // выполняем перебор массива var cookie = jQuery.trim(cookies[i]); // обрезали все отступы if (cookie.substring(0, this.cookieID.length + 1) == (this.cookieID + '=')) { // находим слово cookie cookieValue = decodeURIComponent(cookie.substring(this.cookieID.length + 1)); // выдернули все значения break; } } var properties = cookieValue.split(','); // разбили все значения по , в массив for(var i = 0; i<properties.length;i++){ // перебрали массив var property = properties[i].split(':'); // разбили каждый элемент и this[property[0]] = property[1]; // добавили свойства к объектам } } return true; }; return this; };
|
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" /> <script src="http://www.ageent.ru/templates/ageent/script/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="http://www.ageent.ru/templates/ageent/script/jquery.cookie.js" type="text/javascript"></script> <script> $(document).ready(function(){ var c = new $.cookie(); // создаем объект для работы с куками // блок для записи кук $("button:eq(0)").click(function () { c.text = prompt("Введем значение для text"); c.set({ expires: 300, path: '/'}); }); // блок для удаления кук $("button:eq(1)").click(function () { c.text=""; c.set({ expires: -300, path: '/'}); }); //блок который показывает содержимое всех кук $("button:eq(2)").toggle( function () { $(".too").html(document.cookie); $(this).html("Спрятать куки"); }, function () { $(".too").html(""); $(this).html("Как выглядят куки в реале"); } ); //блок который показывает что мы записали в куки $("div").live("mousemove", function(){ c.get(); // получаем куки if((typeof(c.text) != 'undefined' )) { $(".one").html("Мы записали в куки: <b>text: "+c.text+"</b>"); } if((c.text == "")) { $(".one").html(""); } }); }); </script> </head> <body> <div class="main"> <button>Записать значение в куки</button> <button>Очистить куки</button> <button>Как выглядят куки в реале</button> <div class="one"></div> <div class="too"></div> </div> </body> </html>
|
|
Nice Ajax Poll
Which one of my extensions is the best?
|