简体   繁体   English

我在设置cookie时遇到问题

[英]I am having issues setting up cookies

Im making a mock online ordering site and it requires multivalued cookies but my code wont save anything. 我正在制作一个模拟在线订购网站,它需要多值的cookie,但我的代码不会保存任何东西。 The cookie is supposed to contain the product name, price, and quantity. Cookie应包含产品名称,价格和数量。 Any help would be appreciated. 任何帮助,将不胜感激。

function setCookie(cName, cValue, expDate, cPath, cDomain, cSecure) {
   if (cName && cValue != "") {
      var cString = cName + "=" + escape(cValue);
      cString += (expDate ? ";expires=" + expDate.toGMTString(): "");
      cString += (cPath ? ";path=" + cPath : "");
      cString += (cDomain ? ";domain=" + cDomain : "");
      cString += (cSecure ? ";secure" : "");
      document.cookie = cString;
   }
}

function setField(cName, fName, fValue, expDate, cPath, cDomain, cSecure) {

   if (cName  && fName  && fValue != "") {

      var subkey = fName + "=" + escape(fValue);

      var cValue = null;
      var cookies = document.cookie.split("; ");
      for (var i = 0; i < cookies.length; i++) {
         if (cookies[i].split("=")[0] ==  cName) {
            cValue = cookies[i].slice(cookies[i].indexOf("=") + 1);
            break;
         }
      }
     if (cValue) {
         var foundField = false;
         var subkeys = cValue.split("&");
         for (var i = 0; i < subkeys.length; i++) {
            if (subkeys[i].split("=")[0] == fName) {
               foundField = true;
               subkeys[i] = subkey;
               break;
            }
         }
         if (foundField) cValue = subkeys.join("&")
         else cValue += "&" + subkey;
     } else {
         cValue = subkey;
     }
      var cString = cName + "=" + cValue;
      cString += (expDate ? ";expires=" + expDate.toGMTString(): "");
      cString += (cPath ? ";path=" + cPath : "");
      cString += (cDomain ? ";domain=" + cDomain : "");
      cString += (cSecure ? ";secure" : "");
      document.cookie = cString;
   } 
}

I tried your code in Chrome latest in Windows 7: 我在最新的Windows 7中尝试了Chrome中的代码:

setCookie('test', 'test')

and it works as expected, cookies with this name and value is being set: 它按预期工作,正在设置具有此名称和值的cookie:

console.log(document.cookie)

outputs: 输出:

"test=test;....

If the code doesn't work on your side I can assume it is caused by: 如果代码不适合您,我可以认为它是由以下原因引起的:

  • Wrong values for other params 其他参数的错误值
  • Environment(try the other browser) 环境(尝试其他浏览器)

G'luck! G'luck!

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

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