在javascript中写cookies,在.net中读取(反之毅然) 出现乱码的解决方法
Posted on 2008-11-18 23:55 billpeng 阅读(410) 评论(0) 编辑 收藏 举报最近在学.net和.net ajax,发现在button提交后ajax无法保存视图状态,想了一下,可以用url、cookies或隐藏的textbox来传递
url和textbox方法比较简单就没有多想,主要是测试了cookies的方法,发现只要有中文会就乱码
在网上找了一圈发现解决方法都不理想,主要问题出在于,C#中用UrlEncode来编码或javascript中用的却是unescape来解,反之也是这个道理,总是不行
也试过网上的Javascript自定义函数UrlEncode、UrlDecode,也是不起作用。
后来去看了一下Javascript的函数表,发现原来Javascript中有decodeURI和encodeURI两个函数,可以实现与.net程序之间cookies的完美传递。
真是郁闷的一B啊
.net端
private void setCookie(string name,string value)
{
System.Web.HttpCookie cookie = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value));
cookie.Expires = System.DateTime.Now.AddDays(30);
cookie.Path = "/";
System.Web.HttpContext.Current.Response.AppendCookie(cookie);
}
private string getCookie(string name)
{
if (Request.Cookies[name] != null)
{
return System.Web.HttpUtility.UrlDecode(Request.Cookies[name].Value);
}
else
{
return "";
}
}
{
System.Web.HttpCookie cookie = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value));
cookie.Expires = System.DateTime.Now.AddDays(30);
cookie.Path = "/";
System.Web.HttpContext.Current.Response.AppendCookie(cookie);
}
private string getCookie(string name)
{
if (Request.Cookies[name] != null)
{
return System.Web.HttpUtility.UrlDecode(Request.Cookies[name].Value);
}
else
{
return "";
}
}
Javascript端
function setCookie(name,value)
{
var Days = 30;
var expTime = new Date();
expTime.setTime(expTime.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ encodeURI(value) + ";expires=" + expTime.toGMTString()+";path=/";
}
function getCookie(name)
{
var arrCookies = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arrCookies != null) return decodeURI(arrCookies[2]); return null;
}
{
var Days = 30;
var expTime = new Date();
expTime.setTime(expTime.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ encodeURI(value) + ";expires=" + expTime.toGMTString()+";path=/";
}
function getCookie(name)
{
var arrCookies = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arrCookies != null) return decodeURI(arrCookies[2]); return null;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步