您的位置:首页 > Web前端 > JavaScript

js前台到后台中文传值乱码问题

2015-04-28 10:10 423 查看
今天做普通的前台页面向后台传值,要传值的内容是中文,传到后台打印一看 居然内容变成了 “?????”

于是在网上找了一些方法 :

1、采用decode()方法

页面:

[html] view
plaincopy

Url: '<%=path%>/sfyh/infodata.jsp?type='+encodeURI(ss)

,

后台:

[html] view
plaincopy

String result = java.net.URLDecoder.decode(type,"UTF-8")

2、采用设置字符集的方式

[html] view
plaincopy

request.setCharacterEncoding("utf-8")

3、在页面上定义charset的字符集(最有效 最简单)

[html] view
plaincopy

<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

4、采用转码的方式

页面:

[html] view
plaincopy

Url: '<%=path%>/sfyh/infodata.jsp?type='+encodeURIComponent(ss)

后台:(我使用了这种方式解决了乱码的问题的)

[html] view
plaincopy

result= new String(request.getParameter("type").getBytes("ISO8859-1"),"UTF-8")

乱码问题相关

1.向前台传递数据;

2.向后台传递数据;

3.ajax post 提交数据到服务端时中文乱码解决方法;

4.数组类型参数传递;

1.向前台传递数据:

1.1 字符串数据传递:

这种方式只是单一的向前台传递字符串(比如传递ajax 请求某个数据的结果),通过 response 实现;

1.1.1 Action 类:

1 public String getResult(){
2   HttpServletResponse response=ServletActionContext.getResponse();
3   response.setContentType("text/html;charset=GBK");//解决中文乱码
4     PrintStream out=null; //流
5    try {
6             out = new PrintStream(response.getOutputStream());
7              out.print("向前台传递一个字符串结果");
8         } catch (IOException e) {
9             // TODO Auto-generated catch block
10             e.printStackTrace();
11         }finally{
12         out.flush();
13         out.close();
14     }
15   return null;  //最后返回null
16 }


1.1.2 struts 配置文件:

1 <action name="testAction" class="testAction" method="getResult">
2     <result name="success"></result> <!-- 这里不用填写什么 -->
3   </action>


1.2 对象数据传输:

对象数据通常是已json 格式传输,在 struts2 配置文件内引入 json-default(普通json 格式) 包或者 jackson-json-default(加强型json格式,在返回的json数据中包含对象类型,类似这样的结果("_javaType_":"com.action.TestAction");可以根据业务情况选用,随着业务系统的庞大,我一般用javascript 在前台绑定数据,这样当涉及到判断数据类型时就可以采用这个字段的值来处理:

1.2.1 Action 类:

1     List<Student> lsStudent; //lsStudent 属性要有get\set方法
2     /**
3     * 根据班级ID 获得该班级的学生信息
4     * return 班级所有学生信息
5     */
6    public String getStudentByClassId(){
7
8      HttpRequest request=ServletActionContext.getRequest();
9      String classId=request.getParameter("classId"); //班级ID
10
11      /*
12      *这里的判断很容易出错,如果你用(id!=null)做判断条件,当没有获得值时,id 是一个空的String对象,空对象不能做判断,这就好像你在Java类中这样写代码:  String tb;
13       if(tb==null||tb==""){// 错误:The local variable tb may not have been initialized
14           System.out.println(tb);
15       }
16      */
17      if(null!=id ||!"".equals(id)){
18       lsStudent=TestStudent.getStudentById(id);
19      }
20
21      return SUCCESS;
22    }


1.2.1 struts 配置文件:

1   <action name="testAction" class="testAction" method="getResult">
2          <result name="success" type="strongtype-json">
3          <param name="root">
4          lsStudent <!-- 这里返回action 中要返回的对象(一定要有get/set方法) -->
5          </param>
6          </result>
7       </action>


最终前台会得到这样的json数据:

1 [{"__javaType__":"com.base.Student","name":"张三","age":"10","homeAddr":null,"stuNum":0,"classNum":0},{"__javaType__":"com.base.Student","name":"李四","age":"20","homeAddr":null,"stuNum":0,"classNum":0}]


1.2.3 前台js获得json数据:

1    $.ajax({
2      type:"post",
3      url:"testAction.action",
4      data:{
5      classId:classId
6      },
7      success:function(rs){
8         var studentArray=[]; //前台创建个数组对象保存数据
9        $.each(rs,function(i,item){
10           var student;
11           student.name=item.name;
12           student.id=item.id;
13           student.age=item.age;
14           studentArray.push(student); //将student 对象信息保存到数组对象中
15        });
16      },
17      error:function(){
18      alert("获取数据时发生错误");
19      }
20    });


3.ajax post 提交数据到服务端时中文乱码解决方法:

get 方式提交数据到服务端不会乱码,但对数据量有限制;post 可以提交大数据量,但中文会发生乱码,解决方法:

在JS上用使用 encodeURIComponent 对字符编码处理:

1  studentRuselt=encodeURIComponent(JSON.stringify(result),"utf-8"); //这里用了json2 来将对象转换为json格式,然后在用encodeURIComponent来设置编码;
2
3  $.ajax({
4            type:"post",
5            url:"saveExamQuestionAnswer.action",
6         cache:true,
7         async:true, //这里指定值时不能加双引号(会设置无效)
8            contentType: "application/x-www-form-urlencoded; charset=utf-8",
9            data: {
10                studentRuselt: studentRuselt
11            }
12      )};


Action类上用java.net.URLDecoder.URLDecoder.decode方法转码:

studentRuselt=URLDecoder.decode(studentRuselt,"UTF-8");


这样得到的中文不会乱码,还有另外一个js组件:encodeURI也可以对字符进行处理,提交时它会使用jquery默认编码提交数据,但使用encodeURIComponent 组件指定编码,细节清晰,前台后台处理编码一致这样比较稳妥;

4.数组类型参数传递:

若一个请求中包含多个值,如:(test.action?tid=1&tid=2&tid=3),参数都是同一个,只是指定多个值,这样请求时后台会发生解析错误,应先使用 tradititonal 格式化:

1 $.ajax({
2   type:"post",
3   url:"test.action",
4   data:{
5    tid:[1,2,3]
6    },
7   traditional:true
8
9 });


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: