Example of how to set and obtain cookies in javascript: javascriptcookie

Source: Internet
Author: User
Tags set cookie setcookie

Example of how to set and obtain cookies in javascript: javascriptcookie

This example describes how to set and obtain cookies in javascript. We will share this with you for your reference. The details are as follows:

1. Set cookie

Function setCookie (cookieName, cookieValue, cookieExpires, cookiePath) {cookieValue = escape (cookieValue); // code latin-1 if (cookieExpires = "") {var nowDate = new Date (); nowDate. setMonth (nowDate. getMonth () + 6); cookieExpires = nowDate. toGMTString ();} if (cookiePath! = "") {CookiePath = "; Path =" + cookiePath;} document. cookie = cookieName + "=" + cookieValue + "; expires =" + cookieExpires + cookiePath ;}

2. Get cookie

Function getCookieValue (cookieName) {var cookieValue = document. cookie; var cookieStartAt = cookieValue. indexOf ("" + cookieName + "="); if (cookieStartAt =-1) {cookieStartAt = cookieValue. indexOf (cookieName + "=");} if (cookieStartAt =-1) {cookieValue = null;} else {cookieStartAt = cookieValue. indexOf ("=", cookieStartAt) + 1; cookieEndAt = cookieValue. indexOf (";", cookieStartAt); if (cookieEndAt =-1) {cookieEndAt = cookieValue. length;} cookieValue = unescape (cookieValue. substring (cookieStartAt, cookieEndAt); // decodes latin-1} return cookieValue ;}

Example:

<! Doctype html> 

Note:

Google Chrome only supports online-cookies for security purposes, so it is ineffective during local tests. You need to upload the files to the server for a try.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.