工作過程中遇到一個Js從Cookies裡面取值的需求,Js貌似沒有現成的方法可以指定Key值獲取Cookie裡面對應的值,參閱網上的代碼,簡單實現如下:
1. 服務端代碼,Page_Load裡面Cookies寫入幾個值
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication_TestJS { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Cookies["DONO"].Value = "EDO1406300001"; Response.Cookies["DOID"].Value = "ABCDEFG123456"; Response.Cookies["DOSOURCE"].Value = "WUWUWUWU"; Response.Cookies["DOTYPE"].Value = "2"; } } }
2. 客戶端代碼,頁面添加按鈕和文本框,用於觸發和輸出獲取到的值
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication_TestJS._Default" %> <html> <script language="javascript" type="text/javascript"> function GetCookie() { /*獲取Cookies裡面存放信息 了解其字符串結構*/ var Cookies = document.cookie; document.getElementById("<%=txtContent.ClientID%>").innerText = Cookies; /*處理字符串截取出來需要的目標值*/ var target = "DONO" + "="; if (document.cookie.length > 0) { start = document.cookie.indexOf(target); if (start != -1) { start += target.length; end = document.cookie.indexOf(";", start); if (end == -1) end = document.cookie.length; } } /*目標值賦值給控件*/ document.getElementById("<%=txtTarget.ClientID%>").innerText = document.cookie.substring(start, end); } </script> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="btnGetReq" runat="server" Text="獲取內容" OnClientClick="GetCookie()" /> <br /> <asp:TextBox ID="txtContent" runat="server" Columns="120"></asp:TextBox> <br /> <asp:TextBox ID="txtTarget" runat="server" Columns="120"></asp:TextBox> </div> </form> </body> </html>
3.執行結果,可以看到Cookies就是如第一個文本框中存放結構,根據需要截取相應字符串即可