1. 概述
1.1 問題描述
報表已集成到 Web 頁面中,通過在頁面傳遞參數至報表中時,會發現有時某些參數值,傳遞到報表中是顯示爲問号(???)或亂碼等等一系列不能正常顯示的情況。
1.2 原因分析
這是由於浏覽器和報表服務器的編碼不同,字符多次進行編碼轉換時出現錯誤導緻字符的顯示出現亂碼,尤其是中日韓文和特殊字符更容易出現亂碼問題。
詳細的編碼原理可參考文檔: 編碼
1.3 解決思路
在給報表服務器發送請求之前,使用 JavaScript 先對 URL 編碼,然後再向服務器提交。避免了不同的操作系統、不同的浏覽器、不同的網頁字符集,導緻完全不同的編碼結果。
因爲JavaScript 的輸出總是一緻的,所以就保證了服務器得到的數據是格式統一的。
對 URL 中的中文,包含模板名、參數名字和參數值,進行 encodeURIComponent 或者 encodeURI 編碼。
方法 | 不會對下列字符編碼 | 使用場合 | 示例 |
---|---|---|---|
encodeURI | ASCII 字母、數字、~!@#$&*()=:/,;?+' | 如果需要編碼整個 URL,然後需要使用這個 URL,那麽用encodeURI。 | encodeURI("http://localhost:8075/webroot/decision/view/report?viewlet=中文.cpt") |
encodeURIComponent | ASCII 字母、數字、~!*()' | 如果需要編碼 URL 中的參數的時候,那麽 encodeURIComponent是最好方法。 | "http://localhost:8075/webroot/decision/view/report?viewlet="+encodeURIComponent("中文.cpt") |
所以 encodeURIComponent 比 encodeURI 編碼的範圍更大。 實際例子來說,encodeURIComponent 會把 http:// 編碼成 http%3A%2F%2F 而 encodeURI 卻不會。
2. 示例
2.1 對 URL 中的中文進行編碼
這裏對整個 URL 進行編碼,因此使用 encodeURL,如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script Language="JavaScript">
function frOpen() {
window.location=encodeURI("http://localhost:8075/webroot/decision/view/report?viewlet=GettingStarted.cpt&地區=華東")
}
</script>
</head>
<body>
<input type="button" value="字符轉換1" onclick="frOpen()">
</body>
</html>
當然也可以使用encodeURIComponent只對參數進行編碼:
window.location="http://localhost:8075/webroot/decision/view/report?viewlet="+encodeURIComponent("中文.cpt")
2.2 對 Form 表單中的中文進行編碼
如果是以 Form 表單把參數提交到報表裏面,在提交前調用 encodeURIComponent 進行編碼轉換,如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script>
function autoSubmit() {
var Region1 = document.getElementById('Region'); //獲取到參數 Region 所在文本框
Region1.value = encodeURIComponent(Region.value); //對值參數值進行編碼轉化
Region1.name = encodeURIComponent("地區"); //對參數控件名編碼轉換,如果參數名字爲英文,則不需要此操作
document.FRform.submit();
}
</script>
<body>
<form name=FRform method=post action="http://localhost:8075/webroot/decision/view/report?viewlet=doc/Primary/Parameter/Parameter.cpt">
<input type="text" id="Region" name="地區" value="華東">
<input type="button" name="show" value= "查看" onclick="autoSubmit()"/>
</body>
</html>
2.3 特殊符号處理
如果在需要進行編碼的 URI 的參數中包含特殊字符,比如%,#,$,=,&,/,?,+,@等字符時,使用 encodeURIComponent 對這些特殊字符進行編碼。
例如參數值是”%華%“這樣的字符,完整代碼如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script Language="JavaScript">
function frOpen() {
window.location="http://localhost:8075/webroot/decision/view/report?viewlet=GettingStarted.cpt&"+encodeURIComponent("地區")+"="+encodeURIComponent("%華%")
}
</script>
</head>
<body>
<input type="button" value="字符轉換1" onclick="frOpen()">
</body>
</html>