1. 程式人生 > >徹底解決ajax及後端中文亂碼問題

徹底解決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編碼的,不是對請求的引數編碼。