遇到一个Js从Cookies里面取值的需求,Js貌似没有现成的方法可以指定Key值获取Cookie里面对应的值,参阅网上的代码,简单实现如下:
1. 服务端代码,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. 客户端代码,页面添加按钮和文本框,用于触发和输出获取到的值
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里面存放信息 了解其字符串结构*/
07
var Cookies = document.cookie;
08
document.getElementById("<%=txtContent.ClientID%>").innerText = Cookies;
09
10
/*处理字符串截取出来需要的目标值*/
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
/*目标值赋值给控件*/
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="获取内容" 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.执行结果,可以看到Cookies根据需要截取相应字符串即可
更多信息请查看IT技术专栏