js 编码转换 gb2312 & utf8

方法一:

function gb2utf8(data){ 
     var glbEncode = []; 
     gb2utf8_data = data; 
     execScript("gb2utf8_data = MidB(gb2utf8_data, 1)", "VBScript"); 
     var t=escape(gb2utf8_data).replace(/%u/g,"").replace(/(.{2})(.{2})/g,"%$2%$1").replace(/%([A-Z].)%(.{2})/g,"@$1$2"); 
     t=t.split("@"); 
     var i=0,j=t.length,k; 
     while(++i<j) { 
        k=t[i].substring(0,4); 
        if(!glbEncode[k])  
        { 
           gb2utf8_char = eval("0x"+k); 
           execScript("gb2utf8_char = Chr(gb2utf8_char)", "VBScript"); 
           glbEncode[k]=escape(gb2utf8_char).substring(1,6); 
        } 
        t[i]=glbEncode[k]+t[i].substring(4); 
     } 
     gb2utf8_data = gb2utf8_char = null; 
     return unescape(t.join("%")); 


使用时:xxx.innerHTML=gb2utf8(req.responseBody); 

方法二.

Function bytes2BSTR_GB2312(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn,i,1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn,i+1,1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR_GB2312 = strReturn
End Function

方法三:
<script language="JavaScript">
<!--
function utf8(wide) {
var c, s;
var enc = "";
var i = 0;
while(i<wide.length) {
c= wide.charCodeAt(i++);
// handle UTF-16 surrogates
if (c>=0xDC00 && c<0xE000) continue;
if (c>=0xD800 && c<0xDC00) {
if (i>=wide.length) continue;
s= wide.charCodeAt(i++);
if (s<0xDC00 || c>=0xDE00) continue;
c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
}
// output value
if (c<0x80) enc += String.fromCharCode(c);
else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
}
return enc;
}
var hexchars = "0123456789ABCDEF";
function toHex(n) {
return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}
var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
function encodeURIComponentNew(s) {
var s = utf8(s);
var c;
var enc = "";
for (var i= 0; i<s.length; i++) {
if (okURIchars.indexOf(s.charAt(i))==-1)
enc += "%"+toHex(s.charCodeAt(i));
else
enc += s.charAt(i);
}
return enc;
}
alert(encodeURIComponentNew("中文"))
alert(decodeURIComponent(encodeURIComponentNew("中文")))
// -->
</script>

在java类中配合使用: (适用于ajax)

String dwp = new String(request.getParameter("dwp").getBytes("ISO-8859-1"),"gbk") ;
String dwc = new String(request.getParameter("dwc").getBytes("ISO-8859-1"),"gbk") ;

 

经证实,方法一可行,其余未试。

来源:http://blog.163.com/shn_000/blog/static/17131391200762542857353/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值