//首先說明,我的服務器和頁面編碼都是GBK,所以嘗試了很多種GBK的方式
前台:
function printFunction(){ window.print(); $.ajax({ url : '/tpzssearch/handleRecordLog.action', type : 'post',
//各種嘗試 //processData : true, //scriptCharset:'GBK', // contentType: 'application/x-www-form-urlencoded; charset=gbk', // contentType: "application/x-www-form-urlencoded;charset=gbk", data : {tablename:'<%=java.net.URLEncoder.encode(tablename,"UTF-8")%>', search:'<%= java.net.URLEncoder.encode(session.getAttribute("oradetailQueryString").toString(),"UTF-8")%>', info:'<%=java.net.URLEncoder.encode(rs,"UTF-8")%>' } }); }
后台:
//gbk互轉UTF-8試過、ISO-8859-1互轉gbk試過、ISO-8859-1互轉UTF-8試過
public static String toUTF(String arg) {
if (arg != null && arg.trim().length() > 0) {
try {
arg = new String(arg.getBytes("GBK"), "UTF-8");
} catch (Exception e) {
}
} else {
arg = "";
}
return arg;
}
logModel.setTableName(URLDecoder.decode(request.getParameter("tablename"),"UTF-8"))
最后:就是傳參數時java.net.URLEncoder.encode(tablename,"UTF-8"),接收參數時URLDecoder.decode(request.getParameter("tablename"),"UTF-8"),解決了
解決亂碼的4個方向:
方法一:
在后台中使用request.setCharacterEncoding("UTF-8");
方法二:
$.ajax({
type:'post',
contentType:'application/x-www-form-urlencoded; charset=UTF-8'
});
方法三:
public static String toUTF(String arg) {
if (arg != null && arg.trim().length() > 0) {
try {
arg = new String(arg.getBytes("GBK"), "UTF-8");
} catch (Exception e) {
}
} else {
arg = "";
}
return arg;
}
方法四:
URLDecoder