During the work process, I encountered a need for Js to get the value from cookies. Js seems to have no ready-made method to specify the Key value to get the corresponding value in the cookie. See the code on the Internet, and the simple implementation is as follows:
1. Server code, how many values are written in cookies in Page_Load
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 = "WUWUWUWUWU"; Response.Cookies["DOTYPE"].Value = "2"; } } }2. Client code, page add buttons and text boxes to trigger and output the obtained values
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication_TestJS._Default" %> <html> <script language="javascript" type="text/javascript"> function GetCookie() { /*Get the information stored in the cookies to understand its string structure*/ var Cookies = document.cookie; document.getElementById("<%=txtContent.ClientID%>").innerText = Cookies; /*The target value required for processing string intercept*/ 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; } } /*The target value is assigned to the control*/ 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="get content" 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. The execution result can be seen that cookies are like storing the structure in the first text box, and you can intercept the corresponding string as needed.