[转]通过js encodeURIComponent传到服务器的乱码问题
转自:http://qingfeng825.javaeye.com/blog/890830
一、场景:最近在做一个微博项目,用过微博的人都知道,微博里有话题这个概念,在textarea 里输入##,就代表一个话题。发布微博时使用的ajax方式提交,微博内容会拼到URI中传到服务器端,发现用IE8输入没有任何问题,但是使用IE6时,第二个#号会丢失。
二、解决过程:(1) 在JSP中使用encodeURIComponent来进行编码,两次编码:
Java代码
content=encodeURIComponent(encodeURIComponent(content));
var url="${pageContext.request.contextPath}/BlogAction.do?method=doPublishBlog&content="+content;
(2) 在action中使用解码:
Java代码
String content=(String)request.getParameter("content");
content=URLDecoder.decode(content,"UTF-8");
这个问题得以解决。
三、扩展学习
(1)js 中encodeURI 与 encodeURIComponent的区别
encodeURI 方法返回一个编码的 URI。如果您将编码结果传递给 decodeURI,那么将返回初始的字符串。encodeURI 方法不会对下列字符进行编码:":"、"/"、";" 和 "?"。请使用 encodeURIComponent 方法对这些字符进行编码。经过我测试“#”也属于这个特殊字符的范畴,使用encodeURI编码时#是不会被编码的,所以上面场景的问题依然存在的,对于这种输入的内容,肯定是用encodeURIComponent。
(2)IE对#的不同处理,从下面的header 内容可以看出来。
IE8:
POST /dcwb/BlogAction.do?method=doPublishBlog&content=%23���Ի���%23&decorator=exclude&gridId=&gridName=&videoId=&imageId=&topicId=
IE6:
POST /dcwb/BlogAction.do?method=doPublishBlog&content=%23��������%20&decorator=exclude&gridId=&gridName=&videoId=&imageId=&topicId= HTTP/1.1
posted on 2011-03-26 16:18 LeeXiaoLiang 阅读(369) 评论(0) 收藏 举报
浙公网安备 33010602011771号