遇到問題:在使用xhr發出請求時,請求的url中參數帶中文,這時在後台解析request得不到中文
如:
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open("GET", url);中我的url需要帶中文參數
直接加參數是在後台解析不出來的,所以我使用方法對url進行編碼轉換
在頁面中中文參數傳遞前先轉碼:
function enCode(chineseStr) {
return escape(chineseStr,'utf-8');
}
用經過轉馬後的字符串去生成 url
然後就要在後台進行解碼了
以為沒法直接從request中取到編碼字符串,所以使用方法先取出url,然後再取出url的參數進行解碼
取出url,以及取參數方法
String XXX= getUrlParameter(unescape(request.getQueryString()),"XXX");
//如此獲得的XXX即為解碼後的正確的中文
public String getUrlParameter(String str,String targetstr){
String[] stringarray = str.split("&") ;
for(int i=0;i<stringarray.length;i++){
if(stringarray[i].startsWith(targetstr)){
stringarray=stringarray[i].split("=");
break;
}
}
return stringarray[1];
}
//解碼方法
//以下是對JS的escape進行解碼
private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3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*
* @param s
* @return
*/
public static String unescape(String s) {
StringBuffer sbuf = new StringBuffer();
int i = 0;
int len = s.length();
while (i < len) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
sbuf.append((char) ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
sbuf.append((char) ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
sbuf.append((char) ch);
} else if (ch == '-' || ch == '_' // unreserved : as it was
|| ch == '.' || ch == '!' || ch == '~' || ch == '*'
|| ch == '\'' || ch == '(' || ch == ')') {
sbuf.append((char) ch);
} else if (ch == '%') {
int cint = 0;
if ('u' != s.charAt(i + 1)) { // %XX : map to ascii(XX)
cint = (cint << 4) | val[s.charAt(i + 1)];
cint = (cint << 4) | val[s.charAt(i + 2)];
i += 2;
} else { // %uXXXX : map to unicode(XXXX)
cint = (cint << 4) | val[s.charAt(i + 2)];
cint = (cint << 4) | val[s.charAt(i + 3)];
cint = (cint << 4) | val[s.charAt(i + 4)];
cint = (cint << 4) | val[s.charAt(i + 5)];
i += 5;
}
sbuf.append((char) cint);
} else { // 對應的字符未經過編碼
sbuf.append((char) ch);
}
i++;
}
return sbuf.toString();
}
這時候得到的exfirstWord 就是正確的中文了
問題解決
在使用xhr發出請求時,實際上是向後台發送了一個http的包,只不過這個http的包是封裝的xmlhttprequest,而XMLhttprequest對中文的編碼方式是gb2312的,這樣由於頁面用的是utf-8編碼,所以在後台就會出現問題了。
所以如果你的頁面是gbK或者gb2312編碼的,這樣在用XMLhttprequest就沒有這麼多麻煩了