基础上的不扎实,对很多计算机名词不是很理解,更不能明白他们的基本原理。所以在用程序C#记录cookie,前端用js读入cookie时,费了我不少劲。终于现在弄懂了怎么回事。好了 直接上代码吧。
js
<script src="Scripts/jquery-1.2.6.min.js" type="text/javascript"></script> <script type="text/javascript"> function getCookie(name)//取cookies函数 { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) return unescape(arr[2]); return null; } $(function () { $("#btn").click(function () { $("#read").val(getCookie('username')); }) })
</script>
html
<form id="form1" runat="server"> <div> <input type="text" id="txt" name="txts" /><asp:Button ID="Button1" runat="server" Text="写cookie" onclick="Button1_Click" /><br /> <input type="text" id="read" /><input type="button" id="btn" value="读cookie" /> </div> </form>
c#
public static string test; protected void Page_Load(object sender, EventArgs e) {
} protected void Button1_Click(object sender, EventArgs e) { test = HttpContext.Current.Request.Form["txts"]; test = HttpUtility.UrlEncodeUnicode(test);//对字符串进行js式escape编码。 HttpCookie txtcookie = new HttpCookie("username", test); DateTime dt = new DateTime(); dt = DateTime.Now; TimeSpan ts = new TimeSpan(0, 0, 1, 0); txtcookie.Expires = dt.Add(ts); Response.SetCookie(txtcookie); }
|
请发表评论