有时候我们在使用ajax传递数据的时候总是碰到中文乱码问题,如果各页面,前后台之间传递的编码都是UTF-8那倒还好处理,万一不都是UTF-8呢?
下面提供通用的办法,可以解决中文,日文,韩文等语言乱码问题

//从数据库查出所有对象
List list= service.getList(tableName);
//将list传递到下个界面
session.setAttribute("list", list);



获得传下来的数据,依次填入option,注意option的value值是name编码后的值,这样value值就不会是中文的了,这里使用的是velocity语法!


#set($list= $session.getAttribute("list"))
<select align="center" name=""  id="selection">
        <option value="" > </option>
    	#if ($list)
            #foreach($oneInList in $list)
               <option value="$oneInList.getName_encode()" >$oneInList.getName()</option>
    	   #end
    	#end
</select>
<input id="sendButton" type="button" value="发送" class="btnCmd" />



上面有个方法getName_encoded()是把name编码后的数据,在list的实体类中被实现,看下面代码片段:


private String name;
public String getName() {
	return name;
}
public String getName_encode() {
	return StringUtil.HexEncode(name);
}




获得选择得到的值(注意是编码后的值),然后发起ajax请求到后台处理


jQuery("#sendButton").click(function() {
	var name_encoded=jQuery("#selection").find("option:selected").val();
	jQuery.ajax({
		dataType: "text",
		type:'POST',
		url: sendurl,
		data: encodeURI('name_encoded='+name_encoded),//实际上这里的encodeURI可以不用了,因为name_encoded是编码后的值,不可能是中文的了
		success:function(msg){
                   //这里处理从后台传回来的数据
			alert(msg);
                        },
		error:function(msg){
			alert("msg="+msg);
                        }
		});
	  });



后台接受到编码了的数据,然后反编码,数据变回中文的了


String name_encoded = request.getParameter("name_encoded");
String name_decode= StringUtil.HexDecode(name_encoded);//已经是中文了
//这里处理name_decode后得到sendData,发送到前台
requestgetWriter().write(sendData);
requestgetWriter().flush();
requestgetWriter().close();




利用这种办法可以解决中文乱码问题。其实原理很简单,就是在传到页面之前先用HexEncode方法把中文编码掉,这样就不会传过去中文了,然后再把编码后的数据传到后台用HexDecode方法反编码,这样又恢复中文了。


下面提供HexEncode和HexDecode方法,我把他们放在了StringUtil类中:


/**
     * Encode string to hex string, hex string can use in url
     * @param str
     * @return hex string
     */
    public static String HexEncode(String str) {
    	String hexString = null;
    	if (str != null && str.length() > 0) {
    		char[] digital = "0123456789ABCDEF".toCharArray();
    		StringBuffer sb = new StringBuffer("");
    		try {
    			byte[] bs = str.getBytes("utf-8");
    			int bit;
    			for (int i = 0; i < bs.length; i++) {
    				bit = (bs[i] & 0x0f0) >> 4;
    				sb.append(digital[bit]);
    				bit = bs[i] & 0x0f;
    				sb.append(digital[bit]);
    			}
    		} catch(Exception e) {
    		}
    		hexString = sb.toString();
    	}
    	
    	return hexString;
    }

    /**
     * Decode hex string
     * @param hexString
     * @return
     */
    public static String HexDecode(String hexString) {
    	String str = null;
    	if (hexString != null && hexString.length() > 0) {
    		String digital = "0123456789ABCDEF";
    		char[] hex2char = hexString.toCharArray();
    		byte[] bytes = new byte[hexString.length() / 2];
    		int temp;
    		for (int i = 0; i < bytes.length; i++) {
    			temp = digital.indexOf(hex2char[2 * i]) * 16;
    			temp += digital.indexOf(hex2char[2 * i + 1]);
    			bytes[i] = (byte)(temp & 0xff);
    		}
    		try {
    			str = new String(bytes, "utf-8");
    		} catch (Exception e) {
    		}
    	}
    	return str;
    }



ps:这些都是我在做对日外包中碰到的问题,因为项目中所有的页面都是


<meta http-equiv="Content-type" content="text/html;
charset=Shift_JIS">

编码!