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

JavaScript(js) 前台 参数传递乱码 转码 问题--已解决! 中文字符乱码[转载]

最多使用的应为encodeURIComponent,它是将中文、韩文等特殊字符转换成utf-8格式的url编码,所以如果给后台传递参数需要使用encodeURIComponent时需要后台解码对utf-8支持(form中的编码方式和当前页面编码方式相同)

escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z?

encodeURI不编码字符有82个:!,#,$,&, ',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z?

encodeURIComponent不编码字符有71个:!,??? ',(,),*,-,.,_,~,0-9,a-z,A-Z?
============================================================

做项目时,明明在 web.xml和struts中进行了字符设置 utf-8,但是 从前台 js传过来的参数还是乱码问题,在后台使用request.setCharacterEncoding("UTF-8");还是不行,上网上查了查原来js也有转码的方法,encodeURIComponent() 和 encodeURI(),下面来解决一下问题

例如 js 代码为:

var text= "关键字";

Location.href= "getChildNodeByKeyword.action?keyword="+text;

传到后台的 keyword是乱码

解决方法1:

var text= encodeURIComponent("关键字");

Location.href= "getChildNodeByKeyword.action?keyword="+text;

解决方法2:

var text= "关键字";

Location.href= encodeURI("getChildNodeByKeyword.action?keyword="+text);

自己感觉encodeURIComponent() 和 encodeURI()的区别是 :

见上面的说明!

===================================

系统应用测试中,使用了如下语句:

UTF-8编码,测试成功,服务端获取正常:

decisionMaker = encodeURI(decisionMaker).replace(new RegExp("&", 'g'), "%26");//转码

?

===============Java设置编码格式=========

首先介绍两种字符集 gb2312 和 gbk?
。gb2312 简体中文编码
。gbk 中文字符编码 包括繁体中文

1. 指定jsp文件里内容的的编码方式

?? <%@ page language="java" import="java.util.*"? pageEncoding="gb2312"%>

2. 指定html文件里内容的编码方式
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
3. 当响应用户的请求时,输出到用户浏览器上的编码方式

?? <%@ page contentType="text/html"; charset="gb2312"%>
?? 相当于生成的代码 response.setContentType("text/html; charset=gb2312");

4. 把用户传递过来的参数作为指定的编码
request.setCharacterEncoding("gb2312");

5. 对比
?? request.setCharacterEncoding("gb2312");??????????????? //设置输入编码格式
?? response.setContentType("text/html; charset=gb2312");? //设置输出编码格式

?

[转载 http://blog.csdn.net/jpr1990/article/details/6960298]