上次提出了一个ajax下载中文编码问题,这次有遇到了ajax的上传中文乱麻问题 继续bs各种编码:) 遇到问题:在使用xhr发出请求时,请求的url中参数带中文,这时在后台解析request得不到中文 如: request = new ActiveXObject("Microsoft.XMLHTTP"); request.open("GET", url);中我的url需要带中文参数 直接加参数是在后台解析不出来的,所以我使用方法对url进行编码转换 request = new ActiveXObject("Microsoft.XMLHTTP");
然后就要在后台进行解码了request.open("GET", uriFunc()); //省略了对象定义 //.. function uriFunc() { var separator = "?"; if (uri.indexOf("?") >= 0) separator = "&"; return uri + separator + paramName + "=" + escape(inputField.value,‘utf-8‘); } 以为没法直接从request中取到编码字符串,所以使用方法先取出url,然后再取出url的参数进行解码 取出url,以及取参数方法 String exfirstword = getUrlParameter(unescape(request.getQueryString()),"excludeuser");
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,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F, 0x3F, 0x3F, 0x3F }; /** * 解码 说明:本方法保证 不论参数s是否经过escape()编码,均能得到正确的“解码”结果 * * @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 就是正确的中文了 问题解决 |
|