简体   繁体   English

无法访问JavaScript中的Cookie

[英]Cannot access cookie in javascript

I created a function to get the cookie in javascript : 我创建了一个函数来获取javascript中的cookie:

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

And then I have another function to initialize the cookie : 然后我还有另一个函数来初始化cookie:

  function ChangeVATValue() 
   {
      if ($("#vatEnable").is(':checked')) {
         multipleVAT = 1;
      } else {
         multipleVAT = 0;
      }
      document.cookie = "taxibleC=" + multipleVAT;
      alert(getCookie());
   }

When I used alert(getCookie()); 当我使用alert(getCookie()); , It has the value 1. But when I click to another page, the alert is 0. ,其值为1。但是,当我单击另一页时,警报为0。

Could anyone tell me, why I cannot access the session by using the getCookie() method in the view of my asp.net MVC 3.0 project. 谁能告诉我,为什么我在asp.net MVC 3.0项目的视图中无法通过使用getCookie()方法访问会话。

That is because you cookie might get expire immediatly, if possible se cookie expiration time to certail limit and than access the value of cookie on another page that resolve your issue 那是因为您的cookie可能会立即过期,如果可能的话,cookie的过期时间将达到一定的限制,然后访问另一个可解决您问题的页面上的cookie值

something like 就像是

document.cookie =
  'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

You need to set path in the cookie for accessing in different page 您需要在Cookie中设置path以在其他页面中访问

;path=/

For example, 例如,

document.cookie = 'YOUR COOKIE DATA;path=/'

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

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