ie获取cookie数据,中文乱码;cookie中文乱码终极解决办法
终极解决办法
cookie存中文数据是会出现乱码的,所以在存数据前,得先“编码”,取的时候先“解码”
JS方法-编码:encodeURI("你好") 结果:"%E4%BD%A0%E5%A5%BD"JS方法-解码:decodeURI("%e4%bd%a0%e5%a5%bd") 结果:"你好"c#方法-编码:HttpUtility.UrlEncode("你好") 结果:"%e4%bd%a0%e5%a5%bd"c#方法-解码:HttpUtility.UrlDecode("%E4%BD%A0%E5%A5%BD") 结果:"你好"
推荐文章1:
c#对js的encodeURI() 编码 decodeURI()解码 escape() 编码unescape()解码,decodeURIComponent() ,encodeURICompon加密解密_cplvfx的博客-CSDN博客_c# encodeuri
推荐文章2:
c# .net cookie帮助类CookieHelp.cs,防止cookie乱码,c# 读取cookie乱码,写入cookie乱码_cplvfx的博客-CSDN博客
我cookie存的是json数据
获取到的数据
{"userid":2777000,"uname":"15100000000","pwd":"xxxx","nickName":"姗欏ぇ甯?,"picture":"/Upload/UserInfo/xxx.jpg","truename":"绋a嬮箯","LoginTimes":378,"LastLoginTime":"2022-12-26 16:31:11","InterestLabel":"{\"ArrayID\":[],\"ArrayIDStr\":\"\",\"Object\":[]}","TrueNameStatus":2,"TrueNameStatusDescription":"宸插疄鍚?,"Token":"xxxx","SpreadQRCodeUrl":"/WriteFile/QRCode/551a2390824840cd9161965a98700419.png","userQRCodeUrl":"","orgList":[]}
在cookie拿到数据后,序列化JSON字符串时报错,就是因为【?】问号造成的,因为中文乱码了。
JSON.parse(UserStr)//序列化json
我需要做的时,把从cookie拿到的json字符串,处理成json可序列化的字符串;
处理后的数据
{"userid":2777000,"uname":"15100000000","pwd":"xxxx","nickName":"姗欏ぇ甯","picture":"/Upload/UserInfo/xxx.jpg","truename":"绋a嬮箯","LoginTimes":378,"LastLoginTime":"2022-12-26 16:31:11","InterestLabel":"{\"ArrayID\":[],\"ArrayIDStr\":\"\",\"Object\":[]}","TrueNameStatus":2,"TrueNameStatusDescription":"宸插疄鍚","Token":"xxxx","SpreadQRCodeUrl":"/WriteFile/QRCode/551a2390824840cd9161965a98700419.png","userQRCodeUrl":"","orgList":[]}
处理核心代码
if(IE_Safari.isIE==true)
{//如果是IEconsole.warn('你的浏览器是IE,进入IE业务处理...'); var _userArray=User.split(',');User=""; _userArray.forEach(function(item,index){ if(item.indexOf("?")!=(-1)){ var newItem=item.replace("?","\"");User+=newItem;}else{User+=item;}if((index+1)<_userArray.length){User+=",";} });console.log('处理后:',User);
}
IE_Safari对象是下面的文章里的代码----文章节点 [2023-2-13代码优化-最新完整代码]
IE低版本提示下载新的浏览器js--IEOutTips.zip_cplvfx的博客-CSDN博客_提示ie版本过低js
处理核心代码---解析
第一步:把字符串以“,”逗号分割成数组
var _userArray=User.split(',');
第二步:清空字符串变量
User="";
第三步:使用Array数组的forEach()方法,遍历数据
_userArray.forEach(function(item,index){ });
item:数组里的每条数据
index:当前遍历的数组下标,从0开始
第四步:判断当前数据是否包含问号,包含替换成引号,引号转义
if(item.indexOf("?")!=(-1))
{ var newItem=item.replace("?","\"");User+=newItem;
}else{User+=item;
}
第五步:判断当前数组下标是否小于数组长度,如果小于加逗号
if((index+1)<_userArray.length)
{User+=",";
}