2012-09-17 30 views
1

我在JavaScript中創建了一個cookie。我可以看到並使用該文件中的cookie。我無法在同一個域中的其他頁面中看到並使用相同的Cookie。可能是什麼問題呢?由JavaScript在一頁中設置的Cookie不在另一頁顯示

這是代碼

// Code for set Cookie 

     // Code for set Cookie 
    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; 
       } 
    //Function to call setcookie. In this function I cookie is adding successfully and I can alert the value of the cartcounter cookie. It will be increment one by one for each click 
    function makeSure(skey,name){ 
        var cartcounter=getCookie("cartcounter"); 
        cartcounter=parseInt(cartcounter); 
        chk=0; 
        for(var i=1;i<=cartcounter;i++){ 
         var ckey = getCookie(i+"_skey"); 
         if(ckey==skey){ 
          chk++; 
         } 
        } 
        if(chk==0){ 

         cartcounter=cartcounter+1; 
         setCookie("cartcounter",cartcounter,365); 
         setCookie(cartcounter+"_skey",skey,365); 
         setCookie(cartcounter+"_name",name,365); 
         setCookie(cartcounter+"_val",$("#cnt_"+skey).val(),365); 
         alert(name+" added to your cart successfully.. "); 
        } 
        else 
         alert("You have already added "+name+" item to cart "); 


      } 
    // This is the code in another page to view the cookie. But it show only 0 
      var cartcounter=getCookie("cartcounter"); 
      alert("Counter="+cartcounter); 
+0

發佈一些代碼,也許你做錯了什麼。 –

+0

感謝您的時間Mihai,我發佈了代碼。請看看它。謝謝 –

+0

getCookie函數在哪裏? –

回答

2
  1. 設置你的path。如果您創建的Cookie位於一條路徑/features/feature1/的內部,並且您嘗試從其他「文件夾」訪問它:/items/item1/它將不存在。
    因此,如果您希望在同一個域的每個頁面上都可以訪問path/,則無論它在哪個路徑層次結構中都是如此。

  2. 來講域的,如果你的第一頁是www.mysite.com和您的第二頁上shop.mysite.com或一些其他子域,那麼該cookie也將無法使用,所以設置你的域名等於.mysite.com,這將涵蓋域名所在的任何頁面_____.mysite.com

如果你從不需要#2,那麼不要麻煩設置域。
但是,如果你曾經使用子域名,那麼請記住。

相關問題