日期:2014-05-16  浏览次数:20360 次

通过js encodeURIComponent传到服务器的乱码问题

一、场景:最近在做一个微博项目,用过微博的人都知道,微博里有话题这个概念,在textarea 里输入##,就代表一个话题。发布微博时使用的ajax方式提交,微博内容会拼到URI中传到服务器端,发现用IE8输入没有任何问题,但是使用IE6时,第二个#号会丢失。

?

二、解决过程:(1) 在JSP中使用encodeURIComponent来进行编码,两次编码:

?????

content=encodeURIComponent(encodeURIComponent(content));
var url="${pageContext.request.contextPath}/BlogAction.do?method=doPublishBlog&content="+content;?

?? (2) 在action中使用解码:

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

1 楼 Reset 2011-07-01  
为什么需要进行2次 encodeURIComponent 因为一次encodeURIComponent 传到后台乱码
为什么 一次encodeURIComponent 传到后台乱码?? 

你能告诉我为什么吗??