1. 程式人生 > >js前臺到後臺中文傳值亂碼問題

js前臺到後臺中文傳值亂碼問題

今天做普通的前臺頁面向後臺傳值,要傳值的內容是中文,傳到後臺列印一看 居然內容變成了 “?????”

於是在網上找了一些方法  :

1、採用decode()方法

 頁面:

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

,


  後臺:

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

2、採用設定字符集的方式
  1. request.setCharacterEncoding("utf-8")  


3、在頁面上定義charset的字符集(最有效 最簡單


  1. <%@ page language="java"contentType="text/html; charset=utf-8"
  2.         pageEncoding="utf-8"%>
  3.     <metahttp-equiv="Content-Type"content="text/html; charset=utf-8">



4、採用轉碼的方式

頁面:

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



後臺:(我使用了這種方式解決了亂碼的問題的)
  1. resultnew 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 });
複製程式碼