java ajax发送数据到后台,中文乱码

//首先说明,我的服务器和页面编码都是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;
    }

方法四:

urlencodeURI(url);前台转码一次,java.net.URLDecoder.decode(paperTitle,"UTF-8");后台也转码


你可能感兴趣的:(java ajax发送数据到后台,中文乱码)