js操作Cookie

<head runat="server">
    <title></title>
    <script src="script/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        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
                    return (document.cookie.substring(c_start, c_end))
                }
            }
            return ""
        }

        function setCookie(c_name, value, expiredays) {
            var exdate = new Date()
            exdate.setDate(exdate.getDate() + expiredays)
            document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
            alert('COOKIE创建成功');
        }

        function checkCookie() {
            username = getCookie('username')
            if (username != null && username != "")
            { alert('Welcome again ' + username + '!') }
            else {
                username = prompt('Please enter your name:', "")
                if (username != null && username != "") {
                    setCookie('username', username, 365)
                }
            }
        }
        function DelCookie(name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            document.cookie = name + "=; expires=" + exp.toGMTString();
            alert('指定COOKIE信息清除成功');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="创建COOKIE前赋值" onclick="setCookie('username','I am value',3)" /><input id="Button2" type="button"
            value="查看COOKIE信息" onclick="checkCookie()" /><input id="Button3" type="button" value="清除指定COOKIE信息" onclick="DelCookie('username')"/><input id="Button4" type="button" value="获取指定COOKIE值" onclick="alert(getCookie('username'))"/>
    </div>
    </form>
</body>
</html>

posted @ 2013-05-19 12:36  BicycleBoy  阅读(118)  评论(0编辑  收藏  举报