Js和asp.net各自设置的cookie相互读取的方法

   在Web的开发过程中,避免不了要使用cookie,在这里,我们在前台设置cookie,也可以在后台设置cookie,关键是在前后台设置的cookie,怎么去相互读取,代码如下:
  (1)  前台代码
   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="getFrontSetCookie.aspx.cs"
    Inherits="Study_JavaScript.Html.getFrontSetCookie" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>前后台Cookie的设置和相互读取</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="SM" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        <input type="text" id="txtUser" />
        <br />
        <input type="button" id="btnSetCookie" value="设置Cookie" />
        <br />
        <input type="button" id="btnGetCookie" value="读取后台HttpCookie设置的Cookie" />
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    document.getElementById("btnSetCookie").onclick = function() {
        document.cookie = "UserName=" + document.getElementById("txtUser").value;
        PageMethods.getCookie(getCookie_Success)
    };
    function getCookie_Success(Result) {
        alert(Result);
    }

    
    document.getElementById("btnGetCookie").onclick = function() {
        PageMethods.setCookie(setCookie_Success);
    };
    function setCookie_Success(Result) {
        if (Result) {
            alert(document.cookie);
        }
    }

</script>
(2) 后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace Study_JavaScript.Html
{
    public partial class getFrontSetCookie : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 利用Request.Cookies[""]读取前台通过document.cookie设置的cookie
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public static string getCookie()
        {
            var cook = HttpContext.Current.Request.Cookies["UserName"].Value;
            HttpCookie houtai = new HttpCookie("houtai");
            houtai.Value = "这是后台设置的Cookie";
            return "Cookie读取成功,前台设置的Cookie为" + cook;
        }

        /// <summary>
        /// 后台利用HttpCookie设置Cookie,在前台通过document.cookie读取
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public static bool setCookie()
        {
            HttpCookie houtai = new HttpCookie("houtai"); 
            houtai.Value = "jackie";
            HttpContext.Current.Response.Cookies.Add(houtai);
            return true;
        }

    }
}
总结:(1) 红色部分为后台读取前台设置的cookie的方法.
         (2) 蓝色部分为前台读取后台设置的cookie的方法,如果后台设置多个cookie的话,前台通过document.cookie读取的就是全部的。
posted @ 2014-04-09 21:38  晕菜一员  阅读(600)  评论(0编辑  收藏  举报