一、Javascript裏三種編碼方式
js對文字進行編碼涉及3個函數:escape,encodeURI,encodeURIComponent,
相應3個解碼函數:unescape,decodeURI,d ecodeURIComponent
1、 傳遞參數時需要使用encodeURIComponent,這樣組合的url纔不會被#等特殊字符截斷。
例如:
<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');</script>
2、 進行url跳轉時可以整體使用encodeURI
例如:
Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
3、 js使用數據時可以使用escape
[Huoho.Com編輯]
例如:蒐藏中history紀錄。
4、 escape對0-255以外的unicode值進行編碼時輸出%u****格式,其它情況下escape,encodeURI,encodeURIComponent編碼結果相同。
5、 最多使用的應爲encodeURIComponent,它是將中文、韓文等特殊字符轉換成utf-8格式的url編碼,所以如果給後臺傳遞參數需要使用encodeURIComponent時需要後臺解碼對utf-8支持(form中的編碼方式和當前頁面編碼方式相同)
ps:web項目裏,一般整個工程編碼統一爲utf-8,對應tomcat也要配置URIEncode爲utf-8。這樣中文傳普通值纔不會亂碼
二、三種編碼不編碼的字符:
escape不編碼字符有69個:*,+,-,.,/,@,_,0-9,a-z,A-Z
encodeURI不編碼字符有82個:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent不編碼字符有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z
三、三種編碼對應java的編解碼爲
java.net.URLDecoder / java.net.URLEncoder
對應的是javascript的 encodeURI/decodeURI 和 encodeURIComponent/decodeURIComponent
四、java版本處理escape和unescape
/**
* <B>Java 版本 仿javasciprt Escape/unEscape 方法</B>
*
* @author vernon.zheng
* @version 1.0
*/
public class JSCodeUtils {
public static String escape(String src) {
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length() * 6);
for (i = 0; i < src.length(); i++) {
j = src.charAt(i);
if (Character.isDigit(j) || Character.isLowerCase(j)
|| Character.isUpperCase(j))
tmp.append(j);
else if (j < 256) {
tmp.append("%");
if (j < 16)
tmp.append("0");
tmp.append(Integer.toString(j, 16));
} else {
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
}
public static String unescape(String src) {
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < src.length()) {
pos = src.indexOf("%", lastPos);
if (pos == lastPos) {
if (src.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(src
.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char) Integer.parseInt(src
.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.append(src.substring(lastPos));
lastPos = src.length();
} else {
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
}
最後:
對於漢文字符串來說,假如不期望吧字符串編碼各式轉化爲UTF-8各式的(比如原界面和目的界面的charset是一致的時候),只需要應用escape。假如你的頁面是GB2312或者更多有聯繫的編碼,而接受參數parameter的頁面是UTF-8編碼的,就要採用encodeURI或者encodeURIComponent。