彻底解决ajax及后端中文乱码问题

前端发送带中文的数据:

var searchText = "英语";
    //通过URL传递:需要编码两次
    searchText = encodeURI(searchText);
    searchText = encodeURI(searchText);
    $.ajax({
        type: GET,
        url: search.action + "?searchText=" + searchText,
        data: ,
        contentType: text/json,charset=utf-8,
        dataType: json,
        success: function (data) {
        }
    });
var searchText = "英语";
    //通过ajax数据传递:只需编码一次~
    searchText = encodeURI(searchText);
    $.ajax({
        type: GET,
        url: search.action,
        data: {searchText:searchText},
        contentType: text/json,charset=utf-8,
        dataType: json,
        success: function (data) {
        }
    });

后端接收中文数据:

//都只要反编码一次就行了
queryCon=URLDecoder.decode(queryCon,"utf-8");

后端返回带中文的json数据:

//只需对中文的内容进行编码,如果对整个json字符串进行编码,json中的“”等字符也会被编码导致前端解析json错误
URLEncoder.encode("中文内容","utf-8");

前端解析带中文的json数据:

$.ajax({
        type: GET,
        url: search.action,
        data: {searchText:searchText},
        contentType: text/json,charset=utf-8,
        dataType: json,
        success: function (data) {
            //对应的也只需要对中文进行反编码,例如data.name是中文内容
            alert(decodeURI(data.name));
        }
    });

前端的一些编码方法:

<script type="text/javascript">
	//escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。比如"春节"的返回结果是%u6625%u8282,escape()不对"+"编码 主要用于汉字编码。
	alert(escape("春节"));
	alert(unescape(escape("春节")));
	//encodeURI()是用来对URL编码的函数。 编码整个url地址,但对特殊含义的符号"; / ? : @ & = + $ , #"不进行编码。对应的解码函数是:decodeURI()。
	alert(encodeURI(http://baidu.com?hello=您好&word=文档));
	alert(decodeURI(encodeURI(http://baidu.com?hello=您好&word=文档)));
	//encodeURIComponent() 能编码"; / ? : @ & = + $ , #"这些特殊字符。对应的解码函数是decodeURIComponent()。
	alert(encodeURIComponent(http://baidu.com?hello=您好&word=文档));
	alert(decodeURIComponent(encodeURIComponent(http://baidu.com?hello=您好&word=文档)));
</script>

总结: escape:已经废弃,不推荐使用!!!,而且无法对“/”编码,服务器会报错 encodeURIComponent:传递参数时需要使用encodeURIComponent,推荐使用 encodeURI:用来对请求的URL编码的,不是对请求的参数编码。

经验分享 程序员 微信小程序 职场和发展