开发者

Javascript Cookie Value defined

I am having trouble grasping what the 'value' field of a cookie needs to be. Does the 'value' field need to reference a variable found somewhere with the following javascript code, or is it something completely random?

The reason I ask, is b/c I am trying to put cookies on a project I am working on, but obviously I can't get them to work... here is what I have so far, but my main question is an elaborate definition of the value (physics) field and possibly an example t开发者_如何学运维hat references some Jscript.

function createCookie(child,physics,d82){
  if (d82) {
          var date = new Date();
          date.setTime(date.getTime()+(82*24*60*60*1000));
          var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = child+"="+physics+expires+"; path=/";
}

function readCookie(child) {
  var nameEQ = child + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}


The cookie is sent between the server and the browser as text, so the cookie value has to be a string, or something that can be converted to a string. When you read the cookie you will get the string back.

If you for example store the value 42 in a cookie, it will be converted to the string representation of the number. When you read the cookie, you will get the string "42" back, so if you want it as a numeric value, you have to parse the string.

The cookie value can be anything you want. You could for example store a user's country selection in a cookie, so that you only have to ask the user once:

createCookie('country', country, true);


Think of it as a key value pair. You can give your cookie a name and a value. remember you can have multiple cookies, so the name identifies which on you are referring to, and the value...well I guess it stores the value :)

So for instance I have a cookie called "customerId", the value portion could be "bob"

Refer to http://www.w3schools.com/JS/js_cookies.asp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜