今天在整理代码的时候,发现以前做到一半的功能没有实现。今天完善一下,并无私的将代码分享给大家。

前台代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml" >
 4 <head runat="server">
 5     <title>HTML5学习</title>
 6 </head>
 7 <body>
 8     <form id="form1" runat="server">
 9     <div>
10    
11     <input id="Text1" type="text"  onchange="setCookie('gid_434','434')"/>
12     </div>
13     </form>
14 </body>
15 </html>
16 <script type="text/javascript">
17     function setCookie(name, value) {
18         var Days = 30;
19         var exp = new Date();    
20         exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
21         document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
22     }
23 </script>

后台代码:

using System;
using System.Linq;
using System.Web;
    public partial class GetCookies : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string err_msg = string.Empty;
            if (Request.Cookies.AllKeys.Count() > 0 && Request.Cookies.AllKeys.Contains("gid_434"))
            {
                if (Request.Cookies["gid_434"].Value == null)
                {
                    err_msg = "Cookies:gid_434暂无数据";
                    Response.Write(string.Format("<script>alert('{0}')</script>", err_msg));
                }
                else
                {
                    err_msg = Request.Cookies["gid_434"].Value.ToString();
                    Response.Write(string.Format("<script>alert('{0}')</script>", err_msg));
                }
            }
            else
           {
               err_msg = "Cookies为空";
               Response.Write(string.Format("<script>alert('{0}')</script>", err_msg));
           }
        }
    }