[ASP.net] 透過JavaScript 建立.刪除.讀取Cookie解決方案,包含C#讀取解決中文亂碼問題..
2012-10-05
最近在寫ASP.net的東西,因為要求一堆AJAX處理..
有時候透過Cookie非常的溫馨,所以看了一下有關Cookie的東西..
之前處理過,非常的麻煩所以稍微整理一下最近看的文件…
首先,您得在HTML那頁面加上幾隻Javascript function
//建立Cookie
//name : Key
//value:保存值
//days:預設為天數,如有需求請自行修改
function CreateCookie(name, value, days) {
//需要呼叫編碼,為瞭解決中文問題
value = escape(value);
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
//讀取Cookie
//name : Key
function ReadCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
//unscape是重點,為了完美解決中文問題
}
return null;
}
//刪除cookie
//name: Key
function DeleteCookie(name) {
CreateCookie(name, "", -1);
}
其中要注意的是為了處理中文
所以必須透過Javascript 的 escape() 還有 unescape() 進行編碼跟解碼
這時候我們來看一下我們怎麼呼叫使用..
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="TestViewState.test" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
1:
2: <script src="mcookie.js">
1: </script>
2: </head>
3: <body>
4: <form id="form1" runat="server">
5: <div>
6: <button id="btn1" type="button">
7: 建立Cookie -xxx
8: </button>
9: <button id="btn2" type="button">
10: 讀取Cookie -xxx
11: </button>
12: <button id="btn3" type="button">
13: 刪除Cookie -xxx
14: </button>
15: <script type="text/javascript">
16:
17:
18: $('#btn1').click(function () {
19: CreateCookie('xxx', '許功蓋', 1);
20: });
21:
22: $('#btn2').click(function () {
23: alert(ReadCookie('xxx'));
24: });
25:
26: $('#btn3').click(function () {
27: DeleteCookie('xxx');
28: });
29:
30:
</script><asp:Button ID="btnDelCookie" runat="server" OnClick="Button1_Click" Text="在C#檢查讀取" />
</div>
</form>
</body>
</html>
其中包含透過Javascript 建立帶有中文值的Cookie ,還有刪除,如果刪除過後,C#那一段也會讀不到視為null..
看一下C#端的處理
protected void Button1_Click(object sender, EventArgs e) { var myCookie = Request.Cookies["xxx"].Value; Response.Write( Server.UrlDecode(myCookie));
因為在javascript 那邊經過 escape() 編碼,所以必須要在C#這邊處理 UrlDecode 不然會產生亂碼。
Live Sample :
Download Sample(因為專案原本在側ViewState 所以專案名稱是TestViewState名稱):
參考網址:
Cookie處理:http://www.quirksmode.org/js/cookies.html
中文亂碼處理:http://www.dotblogs.com.tw/limingstudio/archive/2009/11/13/11758.aspx
標籤:
ASP.net
,
C#
,
Javascript
-- Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer. 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...