2009-12-24 3 views
0

를 사용하여 쇼핑 카트와 같은 객체의 상태를 저장하는 곳이 내 샘플 코드웹 데브 - JQuery와 쿠키 plugn

var myCookie; 
var initial_arr = new Array(); 
var myCookie_arr = new Array(); 
var cookieItem; 
$(function() { 

     ... 

     /* This quite works but can't actually achieve what I want */ 
     $('#add_item').click(function(){           
      initial_arr.push(msg.txt); 
      //Update new cookie 
      $.cookie('cookieItem', initial_arr, { expires: 1}); 
      //append on click 
      $('#item-list').append(msg.txt); 
     }); 

     /* This is what I intend to do */ 
     //Update new cookie 
     $.cookie('cookieItem', msg.txt, { expires: 1}); 
     // add elements at the end of my cookie array 
     myCookie_arr.push($.cookie('cookieItem')); 

     ... 

    $(window).load(function() { 

     ... 

     alert(myCookie_arr); 
     for(var i= 0; i < myCookie_arr; i++) { 
      //append on visiting other pages 
      $('#item-list').append(myCookie_arr[i]); 
     } 

     ...    

     if(cookieItem) { 
      $('#item-list').append($.cookie('cookieItem')); 
     } else { 
      $('#cat').hide();       
     } 
    }); 
}); 

답변

0

내가 여기 other question을 보았다이고 그것을 당신이 추가, 제거하거나 선택을 취소 할 나타납니다 쿠키 배열 이 기본 기능을 함께 사용하면 어떻게 할 수 있는지 알 수 있습니다.

function addToCookie(arr,item){ 
arr.push(item) 
$.cookie('cookieItem', arr, {expires: 1}); 
// add item to cart 
return arr; 
} 

function removeFromCookie(arr,item){ 
arr.splice(arr.indexOf(item) , 1); 
$.cookie('cookieItem', arr, {expires: 1}); 
// remove item from cart 
return arr; 
} 

function clearCookie(arr){ 
$.cookie('cookieItem', null); 
// empty the cart 
return []; 
} 
+0

고맙습니다. 이것은 정말 도움이되었습니다. – mukamaivan

0

장바구니 쿠키를 전혀 잊어 버릴 것을 강력히 권장합니다. ajax 호출을 사용하여 서버 측의 세션에서 장바구니를 유지 관리하십시오. 사양에도 불구하고 쿠키 값은 대부분 웹 브라우저에서 이 아니며은 무제한입니다.

+0

그것은 밝은 아이디어가 될 수 있지만 처음에는 시도가 ... 고맙습니다. – mukamaivan