工作过程中遇到一个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>
标签:
Cookies,值
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com
暂无“js从Cookies里面取值的简单实现”评论...