js從Cookies里面取值的簡單實現(xiàn)

字號:


    遇到一個Js從Cookies里面取值的需求,Js貌似沒有現(xiàn)成的方法可以指定Key值獲取Cookie里面對應(yīng)的值,參閱網(wǎng)上的代碼,簡單實現(xiàn)如下:
    1. 服務(wù)端代碼,Page_Load里面Cookies寫入幾個值
    01
    using System;
    02
    using System.Collections.Generic;
    03
    using System.Web;
    04
    using System.Web.UI;
    05
    using System.Web.UI.WebControls;
    06
    07
    namespace WebApplication_TestJS
    08
    {
    09
    public partial class _Default : System.Web.UI.Page
    10
    {
    11
    protected void Page_Load(object sender, EventArgs e)
    12
    {
    13
    Response.Cookies["DONO"].Value = "EDO1406300001";
    14
    Response.Cookies["DOID"].Value = "ABCDEFG123456";
    15
    Response.Cookies["DOSOURCE"].Value = "WUWUWUWU";
    16
    Response.Cookies["DOTYPE"].Value = "2";
    17
    }
    18
    }
    19
    }
    2. 客戶端代碼,頁面添加按鈕和文本框,用于觸發(fā)和輸出獲取到的值
    01
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication_TestJS._Default" %>
    02
    <html>
    03
    <script language="javascript" type="text/javascript">
    04
    function GetCookie()
    05
    {
    06
    /*獲取Cookies里面存放信息 了解其字符串結(jié)構(gòu)*/
    07
    var Cookies = document.cookie;
    08
    document.getElementById("<%=txtContent.ClientID%>").innerText = Cookies;
    09
    10
    /*處理字符串截取出來需要的目標(biāo)值*/
    11
    var target = "DONO" + "=";
    12
    if (document.cookie.length > 0)
    13
    {
    14
    start = document.cookie.indexOf(target);
    15
    if (start != -1)
    16
    {
    17
    start += target.length;
    18
    end = document.cookie.indexOf(";", start);
    19
    if (end == -1) end = document.cookie.length;
    20
    }
    21
    }
    22
    23
    /*目標(biāo)值賦值給控件*/
    24
    document.getElementById("<%=txtTarget.ClientID%>").innerText = document.cookie.substring(start, end);
    25
    }
    26
    </script>
    27
    <head runat="server">
    28
    <title></title>
    29
    </head>
    30
    <body>
    31
    <form id="form1" runat="server">
    32
    <div>
    33
    <asp:Button ID="btnGetReq" runat="server" Text="獲取內(nèi)容" OnClientClick="GetCookie()" />
    34
    <br />
    35
    <asp:TextBox ID="txtContent" runat="server" Columns="120"></asp:TextBox>
    36
    <br />
    37
    <asp:TextBox ID="txtTarget" runat="server" Columns="120"></asp:TextBox>
    38
    </div>
    39
    </form>
    40
    </body>
    41
    </html>
    3.執(zhí)行結(jié)果,可以看到Cookies根據(jù)需要截取相應(yīng)字符串即可