简体   繁体   English

浏览器cookie不起作用

[英]Browser cookie doesn't work

I am trying to send data from one html page to another. 我正在尝试将数据从一个html页面发送到另一个页面。 I am using cookies to save info that will be retrieve by the another wabpage. 我正在使用cookie来保存将由另一个wabpage检索的信息。 However, when the next page wants to get the value of the cookie, it is empty. 但是,当下一页想要获取cookie的值时,它是空的。 I think the cookie is being lost when I'm going from one page to another. 我认为当我从一个页面转到另一个页面时,cookie正在丢失。

Thank You!!!! 谢谢!!!! (Is there better alternative?) (有更好的选择吗?)

This is how I tried to accomplish this task in JavaScript: 这就是我尝试在JavaScript中完成此任务的方式:

For saving data inside cookies (only for 1 day) 用于在cookie中保存数据(仅限1天)

 //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 获取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. 虽然编写自己的cookie库是一种很好的做法,但它可能有点令人沮丧。 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 我建议使用(和/或审核)现有的库,例如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. 作为cookie的替代方案,您可能会发现HTML5功能localStorage和sessionStorage是有用的,具体取决于您的用例。 For more information, see http://diveintohtml5.info/storage.html and/or http://www.html5rocks.com/en/features/offline 有关详细信息,请参阅http://diveintohtml5.info/storage.html和/或http://www.html5rocks.com/en/features/offline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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