JQuery读取gb2312编码文件

2013-10-18  金城  2631

以后统一用成utf8格式就免了各方面的麻烦。但是对于以前的项目过渡时期还的继续使用。

JQuery读取GB2312格式编码的文件有时会发现读出来乱码,最简单的解决方式是在要读取的文件中明确指示GB2312字符集。

读取gb2312文件

方法一

在ASP中

<% response.charset=”gb2312”%>

在php中

<?php header('Content-Type:text/html;charset=utf-8');?>

在jsp中

<%@ page contentType="text/html;charset=gb2312"%>

方法二

在gb2312端将中文字符转义或加密为asc字符,在JQuery端用js转义或解密为中文字符。

asp测试文件

<script type="text/javascript">alert(unescape('<%=escape("中文")%>'))</script>

 

以上是读取gb2312文件,如果给gb2312文件传递参数就复杂点了。

javascript端需要将中文字符转义为asc字符,gb2312文件段再反转义为中文。一般用 js 的escape 函数

让后再gb2312文件端,使用javascript 的 unescape函数 或编写 unescape函数 同功能的函数进行反转义。

<%
'asp 中 用vbscript 编写的 unescape()函数,如果脚本语言是javascript 则直接可以使用unescape函数。
Function VBsUnEscape(byVal str)
  dim i,s,c
  s=""
  str=str&""
  For i=1 to Len(str)
     c=Mid(str,i,1)
     If Mid(str,i,2)="%u" and i<=Len(str)-5 Then
        If IsNumeric("&H" &Mid(str,i+2,4)) Then
           s = s &CHRW(CInt("&H" &Mid(str,i+2,4)))
           i = i+5
        Else
           s = s &c
        End If
     ElseIf c="%" and i<=Len(str)-2 Then
        If IsNumeric("&H" &Mid(str,i+1,2)) Then
           s = s &CHRW(CInt("&H" &Mid(str,i+1,2)))
           i = i+2
        Else
           s = s &c
        End If
     Else
        s = s &c
     End If
  Next
  VBsUnEscape = s
End Function
'escape()函数实现,不变的7个符号: *(42) +(43) -(45) .(46) /(47) @(64) _(95)
Function VBsEscape(byVal str)
  dim i,s,c,a
  s=""
   str=str&""
  For i=1 to Len(str)
     c=Mid(str,i,1)
     a=ASCW(c)
     If (a>=48 and a<=57) or (a>=65 and a<=90) or (a>=97 and a<=122) Then
        s = s &c
     ElseIf InStr("@*_+-./",c)>0 Then
        s = s &c
     ElseIf a>0 and a<16 Then
        s = s &"%0" &Hex(a)
     ElseIf a>=16 and a<256 Then
        s = s &"%" &Hex(a)
     Else
        s = s &"%u" &Hex(a)
     End If
  Next
  VBsEscape = s
End Function
%>


<?php
# php 中的转义函数
function escape($str){ 
  preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r); 
  $ar = $r[0]; 
  foreach($ar as $k=>$v){ 
    if(ord($v[0]) <128) 
      $ar[$k] = rawurlencode($v); 
    else
      $ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v)); 
  } 
  return join("",$ar); 
}

function unescape($str){ 
  $str = rawurldecode($str); 
  preg_match_all("/(?:%u.{4})|.+/",$str,$r); 
  $ar = $r[0]; 
  foreach($ar as $k=>$v){ 
  if(substr($v,0,2) == "%u" &&strlen($v) == 6) 
     $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4))); 
  } 
  return join("",$ar); 
}
?>