简体   繁体   中英

Browser cookie doesn't work

I am trying to send data from one html page to another. I am using cookies to save info that will be retrieve by the another wabpage. However, when the next page wants to get the value of the cookie, it is empty. I think the cookie is being lost when I'm going from one page to another.

Thank You!!!! (Is there better alternative?)

This is how I tried to accomplish this task in JavaScript:

For saving data inside cookies (only for 1 day)

 //HTML page 1
 setCookie("myCookie", myData, 1);

where

function setCookie(c_name, value, exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

For getting cookie

//HTML page 2
var cookieValue = getCookie("myCookie");

where

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

While writing your own cookies library is good practice, it can be a little frustrating. I would recommend the use of (and/or reviewing) an existing library such as cookie.js - http://code.google.com/p/cookie-js/source/browse/trunk/cookie.js

As an alternative to cookies, you might find that the HTML5 features localStorage and sessionStorage are helpful, depending on your use case. For more information, see http://diveintohtml5.info/storage.html and/or http://www.html5rocks.com/en/features/offline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM