JavaScript操作Cookie方法实例分析
本文实例讲述了JavaScript操作Cookie方法。分享给大家供大家参考。具体如下:
//Mymethodsforsetting,readinganddeletingcookies. //Ihavemethodstocheckfortheexistenceofcookienamesorvalues, //toretrievebynameorvalue,andtocreateaformattedstringof //allthecookies. //Mysite:andrew.dx.am varSetCookie=function(name,value,expires,path,domain,secure){ //ThecallershouldTrimthename/valuepair,ifrequired. //Setsthename/valuepair(encoded);'expires'istheno.ofdays. varexpires_date; if(expires){ expires_date=newDate(); expires_date.setDate(expires_date.getDate()+expires); } document.cookie=encodeURIComponent(name)+"="+ encodeURIComponent(value)+ ((expires)?";expires="+expires_date.toUTCString():"")+ ((path)?";path="+path:"")+ ((domain)?";domain="+domain:"")+ ((secure)?";secure":""); }; varDeleteCookie=function(name,path,domain){ //ThecallershouldTrimthename/valuepair. //Encodesthenamebeforedeleting. document.cookie=encodeURIComponent(name)+"="+ ((path)?";path="+path:"")+((domain)?";domain="+ domain:"")+";expires=Fri,01-Jan-201000:00:01UTC"; }; varDelAllCookies=function(){ varcurrDate=newDate(),i,theCookie=document.cookie.split(";"); currDate=currDate.toUTCString(); i=theCookie.length; while(i--){ document.cookie=theCookie[i]+";expires="+currDate; } }; varEscapeReg=function(str){ //Helperfn:Escapescharactersforuseinaregularexpression. returnstr.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"); }; //ThefollowingfourfunctionsdonotTrimthenameorvalue //-thecallingfnsshoulddothis. varCNameExists=function(cookie_name){//case-insensitive vartestName,myReg; if(document.cookie.length==0)returnfalse; testName=EscapeReg(cookie_name); myReg=newRegExp('(^|;)?'+testName+'=([^;]*)(;|$)','i'); returnmyReg.test(decodeURIComponent(document.cookie)); }; varCValueExists=function(cookie_value){//caseinsensitive vartestName,myReg; if(document.cookie.length==0)returnfalse; testName=EscapeReg(cookie_value); myReg=newRegExp('(=)'+testName+'(;|$)','i'); returnmyReg.test(decodeURIComponent(document.cookie)); }; varCNameGet=function(cookie_value){//case-insensitive vartestName,myReg,results; if(document.cookie.length==0)return''; testName=EscapeReg(cookie_value); myReg=newRegExp('(^|;)?([^=]*)='+testName+'(;|$)','i'); results=decodeURIComponent(document.cookie).match(myReg); return(results)?results[2]:''; }; varCValueGet=function(cookie_name){//case-insensitive vartestName,myReg,results; if(document.cookie.length==0)return''; testName=EscapeReg(cookie_name); myReg=newRegExp('(^|;)?'+testName+'=([^;]*)(;|$)','i'); results=decodeURIComponent(document.cookie).match(myReg); return(results)?results[2]:''; }; varCookieStr=function(){ //Returnsastring(withlinebreaks)whichcouldbe //placedin,forexample,atextarea. returndecodeURIComponent(document.cookie). replace(/([^=;]+)=([^;]*)[;\s]*/g,'$1($2)\n')||''; };
希望本文所述对大家的javascript程序设计有所帮助。