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") 注:如果URL參數中包含「+」號,需要進行兩次編碼,例如encodeURlComponent(encodeURlComponent('+1')) |
所以 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 對這些特殊字元進行編碼。
注:如果URL參數中包含「+」號,需要進行兩次編碼,例如encodeURlComponent(encodeURlComponent('+1'))
例如參數值是”%華%“這樣的字元,完整程式碼如下:
<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>