Dzwebs.Net

撰写电脑技术杂文十余年

JavaScript另类用法--读取和写入cookie

Admin | 2007-12-17 20:19:38 | 被阅次数 | 9723

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

        写入和读取Cookie是一种常见的功能,可惜JavaScript对此的直接支持并不算完善,下面是几个操作Cookie的函数,用起来还是蛮方便的。


function getExpDate(days, hours, minutes) {

    var expDate = new Date( );

    if (typeof days == "number" && typeof hours == "number" &&

        typeof hours == "number") {

        expDate.setDate(expDate.getDate( ) + parseInt(days));

        expDate.setHours(expDate.getHours( ) + parseInt(hours));

        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));

        return expDate.toGMTString( );

    }

}

  
function getCookieVal(offset) {

    var endstr = documents.cookie.indexOf (";", offset);

    if (endstr == -1) {

        endstr = documents.cookie.length;

    }

    return unescape(documents.cookie.substring(offset, endstr));

}

  
function getCookie(name) {

    var arg = name + "=";

    var alen = arg.length;

    var clen = documents.cookie.length;

    var i = 0;

    while (i < clen) {

        var j = i + alen;

        if (documents.cookie.substring(i, j) == arg) {

            return getCookieVal(j);

        }

        i = documents.cookie.indexOf(" ", i) + 1;

        if (i == 0) break;

    }

    return "";

}

  

function setCookie(name, value, expires, path, domain, secure) {

    documents.cookie = name + "=" + escape (value) +

        ((expires) ? "; expires=" + expires : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

  

function deleteCookie(name,path,domain) {

    if (getCookie(name)) {

        documents.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}

将上面的几个js命名为cookie.js,下面演示其基本用法

<script type="text/javascript" src="cookie.js"></script>

 

<script type="text/javascript">

   function foo()

   {

         var name = document.getElementById("name").value;

         if(name)

         {

              setCookie("name",name);

         }

         document.getElementById("show").innerHTML+=("NEWEST NAME :"+ getCookie("name") + "<br>");

   }

</script>

Chapter 1.9 example

<br>

<input type="text" id="name" size="20" />

<input type="button" value="setCookie" onclick="foo()" />

<div id="show"></div>


该杂文来自: 网页制作杂文

上一篇:网站优化之14条专家经验

下一篇:常用JavaScript的表单提交(验证)判断函数

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计