- 注册时间
- 2010-11-11
- 最后登录
- 2025-5-27
- 阅读权限
- 200
- 积分
- 14361
- 精华
- 2
- 帖子
- 843
  

TA的每日心情 | 无聊 2025-5-27 03:37:20 |
---|
签到天数: 366 天 [LV.9]以坛为家II
我玩的应用:
  
|
先分析一下为何会出现中文乱码的问题。原因很简单:xmlhttp得到response时假定response是utf8编码的,它把含gb2312编码的html当成utf8格式,因此,出现了中文乱码。
那么,除了使用asp服务器端脚本技术外,就没有客户端的解决办法吗?答案是:有!
本人使用vbscript客户端脚本,成功实现了不使用asp,解决了xmlhttp 抓取 html页面时出现中文乱码的问题。
为何使用vbscript,而不是大家常用的jscript?xmlhttp的responsebody返回的是一个unsigned bytes数组。vbscript提供了许多用于操作字符串和格式化数据的函数,以及访问安全数组的方法。这些函数或方法在jscript中并不存在。这里我们需要使用vbscript的内置函数:midb、ascb、lenb等,来访问responsebody。
说句题外话,我不是在强调vbscript比jscript好,而是二者都有自己的特点。第一次在csdn上写文章,谢谢大家支持。写这边文章有两个目的:一、锻炼自己;二、希望大家遇到问题时,要学会分析问题,做到有的放矢,知其然也知其所以然。
我给出代码test.htm,它包括了获取自身代码和获取其他网页代码两种应用,具体脚本如下:
- <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
- <!-- 作者:小林,sulins@tom.com -->
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=gb2312">
- </head>
- <script language=vbscript>
- function bytes2bstr(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 = strreturn
- end function
- function viewsource1()
- dim xmlhttp
- set xmlhttp = createobject("microsoft.xmlhttp")
- xmlhttp.open "get", document.location.href, false
- xmlhttp.setrequestheader "content-type","text/xml"
- xmlhttp.send
- dim html
- html = bytes2bstr(xmlhttp.responsebody)
- msgbox html
- end function
- function viewsource2()
- dim xmlhttp
- set xmlhttp = createobject("microsoft.xmlhttp")
- xmlhttp.open "get", "http://www.google.com", false
- xmlhttp.setrequestheader "content-type","text/xml"
- xmlhttp.send
- dim html
- html = bytes2bstr(xmlhttp.responsebody)
- msgbox html
- end function
- </script>
- <body bgcolor=gainsboro style=border:1pt solid white>
- <table class=text>
- <tr>
- <td class=text>xmlhttp get html页面时的中文乱码之完全客户端script解决方案</td>
- </tr>
- <tr>
- <td class=button><button onclick=viewsource1()>查看自身的网页代码</button></td>
- </tr>
- <tr>
- <td class=button><button onclick=viewsource2()>查看google主页代码</button></td>
- </tr>
- </table>
- </body>
- </html>
复制代码
|
|