js 로 쿠키 를 조작 하여 탐색 기록 을 저장 합 니 다.

7802 단어 cookie
cookie ... 과 session 예.
자주 사용 되 는 정보 저장 방식.Cookie 는 클 라 이언 트 가 개발 한 사용자 정 보 를 저장 할 수 있 는 곳 입 니 다.Session 은 서버 메모리 에 사용자 정 보 를 저장 하 는 곳 입 니 다.
JavaScript 는 클 라 이언 트 에서 실행 되 는 스 크 립 트 이기 때문에 일반적으로 Session 을 설정 할 수 없습니다. Session 은 서버 에서 실행 되 기 때 문 입 니 다.쿠키 는 클 라 이언 트 에서 실행 되 기 때문에 JS 로 쿠키 를 설정 할 수 있 습 니 다. 만약 에 이러한 상황 이 있다 고 가정 하면 특정한 사례 절차 에서 A 페이지 에서 B 페이지 로 이동 합 니 다. 만약 에 A 페이지 에서 JS 를 변수 temp 으로 특정한 변수의 값 을 저장 하면 B 페이지 에서 도 JS 를 사용 하여 temp 의 변수 값 을 참조 해 야 합 니 다.JS 의 전역 변수 나 정적 변수의 수명 주기 가 제한 되 어 있 습 니 다. 페이지 가 이동 하거나 페이지 가 닫 힐 때 이 변수의 값 은 다시 불 러 옵 니 다. 즉, 저장 효 과 를 얻 지 못 합 니 다.이 문 제 를 해결 하 는 가장 좋 은 방안 은 쿠키 를 사용 하여 이 변수의 값 을 저장 하 는 것 입 니 다. 그러면 어떻게 쿠키 를 설정 하고 읽 습 니까?먼저 쿠키 의 구 조 를 조금 알 아야 합 니 다. 쉽게 말 하면 쿠키 는 키 값 이 맞 는 형식 으로 저 장 됩 니 다. 즉, key = value 의 형식 입 니 다.각 쿠키 사 이 는 일반적으로 ";" 로 구 분 됩 니 다.JS 설정 쿠키: A 페이지 에 변수 username 의 값 ("jack") 을 쿠키 에 저장 하려 면 key 값 이 name 이 고 해당 하 는 JS 코드 는 document. cookie = "name =" + username 입 니 다.  JS 쿠키 읽 기: 쿠키 에 저 장 된 내용 이 name = jack 이 라 고 가정 합 니 다.password=123 B 페이지 에서 변수 username 의 값 을 가 져 오 는 JS 코드 는 다음 과 같 습 니 다: var username=document.cookie.split(";")[0].split("=")[1];  //JS 조작 cookies 방법! /쿠키 기능 쓰기 setCookie(name,value){   var Days = 30;   var exp = new Date();   exp.setTime(exp.getTime() + Days*24*60*60*1000);   document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();      var strsec = getsec(time);   var exp = new Date();   exp.setTime(exp.getTime() + strsec*1);   document.cookie = name + "="+ escape (value) + ";expires=" + exp. toGMTString ();} / / 쿠키 기능 읽 기 getCookie(name){   var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");    if(arr=document.cookie.match(reg))       return (arr[2]);   else      return null;} / / 쿠키 기능 삭제 delCookie(name){   var exp = new Date();   exp.setTime(exp.getTime() - 1);   var cval=getCookie(name);   if(cval!=null)      document.cookie= name + "="+cval + "; expires =" + exp. toGMTString ();} / / 예제 setCookie ("name", "hayden"), alert (getCookie ("name"), / 사용자 정의 만 료 시간 을 설정 해 야 한다 면 / / 위의 setCookie 함 수 를 아래 두 함수 로 바 꾸 면 됩 니 다. / / 프로그램 코드 function setCookie(name,value,time){   var strsec = getsec(time);   var exp = new Date();   exp.setTime(exp.getTime() + strsec*1);   document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();}function getsec(str){  alert(str);  var str1=str.substring(1,str.length)*1;  var str2=str.substring(0,1);  if (str2=="s")  {      return str1*1000;  }  else if (str2=="h")  {     return str1*60*60*1000;  }  else if (str2=="d")  {     return str1*24*60*60*1000;  }}//이것 은 만 료 시간 을 설정 하 는 사용 예제 가 있 습 니 다. / s20 은 20 초 / h 를 대표 하 는 시간 입 니 다. 예 를 들 어 12 시간 은 h12 / d 는 일수 이 고 30 일 은 d30setCookie ("name", "hayden", "s20") 입 니 다.
-----------------------
설명: 최근 에 사용자 가 방문 한 제품 페이지 를 기록 하 는 기능 을 만 들 었 습 니 다. 제 생각 은 고객 이 제품 페이지 에 들 어 갈 때마다 JS 를 사용 하여 제품 정 보 를 json 형식 으로 쿠키 에 저장 하 는 것 입 니 다. 기록 을 조회 하 는 디 스 플레이 는 쿠키 에서 읽 은 다음 json 으로 해석 하여 html 요 소 를 생 성 하 는 것 입 니 다. 사용자 가 여러 페이지 를 동시에 열 수 있 기 때 문 입 니 다. 이 몇 개의 페이지 는 쿠키 에서 읽 은 것 입 니 다.페이지 에 탐색 기록 이 있 을 수 있 습 니 다. 탐색 기록 을 표시 하 더 라 도 1 초 에 한 번 씩 새로 고침 하기 위해 서 는 js 파일 2 개, history. js, 관건 적 인 채 팅 기록 저장 과 읽 기 코드 를 사용 해 야 합 니 다. json. js, json 을 처리 합 니 다.
http://www.cnblogs.com/qinying/archive/2010/09/15/1826846.html
history.js
   
var addHistory=function(num,id){
    stringCookie=getCookie('history');
    var stringHistory=""!=stringCookie?stringCookie:"{history:[]}";
    var json=new JSON(stringHistory);
    var e="{num:"+num+",id:"+id+"}";
    json['history'].push(e);//        
    setCookie('history',json.toString(),30);
}
//      
var DisplayHistory=function(){
    var p_ele=document.getElementById('history');
     while (p_ele.firstChild) {
      p_ele.removeChild(p_ele.firstChild);
     }
   
    var historyJSON=getCookie('history');
    var json=new JSON(historyJSON);
    var displayNum=6;
    for(i=json['history'].length-1;i>0;i--){
        addLi(json['history'][i]['num'],json['history'][i]['id'],"history");
        displayNum--;
        if(displayNum==0){break;}
    }
}
//    li  
var addLi=function(num,id,pid){
    var a=document.createElement('a');
    var href='product.action?pid='+id;
    a.setAttribute('href',href);
    var t=document.createTextNode(num);
    a.appendChild(t);
    var li=document.createElement('li');
    li.appendChild(a);
    document.getElementById(pid).appendChild(li);
}
//  cookie
var setCookie=function(c_name,value,expiredays)
{
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    cookieVal=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
//    alert(cookieVal);
    document.cookie=cookieVal;
}
//  cookie
function getCookie(c_name)
{
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=")
      if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1 
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1) c_end=document.cookie.length
//        document.write(document.cookie.substring(c_start,c_end)+"<br>");
        return unescape(document.cookie.substring(c_start,c_end))
        } 
      }
    return ""
}
json.js
   
var JSON = function(sJSON){
    this.objType = (typeof sJSON);
    this.self = [];
    (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
}
JSON.prototype = {
    toString:function(){
        return this.getString();
    },
    valueOf:function(){
        return this.getString();
    },
    getString:function(){
        var sA = [];
        (function(o){
            var oo = null;
            sA.push('{');
            for(var i in o){
                if(o.hasOwnProperty(i) && i!='prototype'){
                    oo = o[i];
                    if(oo instanceof Array){
                        sA.push(i+':[');
                        for(var b in oo){
                            if(oo.hasOwnProperty(b) && b!='prototype'){
                                sA.push(oo[b]+',');
                                if(typeof oo[b]=='object') arguments.callee(oo[b]);
                            }
                        }
                        sA.push('],');
                        continue;
                    }else{
                        sA.push(i+':'+oo+',');
                    }
                    if(typeof oo=='object') arguments.callee(oo);
                }
            }
            sA.push('},');
        })(this.self);
        return sA.slice(0).join('').replace(/\[object object\],/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
    },
    push:function(sName,sValue){
        this.self[sName] = sValue;
        this[sName] = sValue;
    }
}
    
   
<script type="text/javascript" src="../js/json.js"></script>
<script type="text/javascript" src="../js/history.js"></script>
<ul id="history">
</ul>
<script> 
addHistory(15810782304,2);
addHistory(64654665,2);
addHistory(6843212,2);
addHistory(84984432521,2);
setInterval("DisplayHistory()",1000);
</script>

좋은 웹페이지 즐겨찾기