XMLHTTP Get HTML页面时的中文乱码之完全客户端Script解决方案
先分析一下为何会出现中文乱码的问题。原因很简单: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>
强强强~~,太好了,谢谢
static/image/common/sigline.gif
http://img2081.poco.cn/mypoco/myphoto/20110822/16/64165363201108221627279573116820626_000.jpg 我也来看了,很不错,收藏了
static/image/common/sigline.gif
1.di-guo.info 2.di-guo.info
3.di-guo.info 4.di-guo.info
5.di-guo.info 6.di-guo.info 7.di-guo.info 8.di-guo.info
9.di-guo.info 看后感悟了点,收下了
static/image/common/sigline.gif
宜州蜀门sf 柯坪魔力宝贝私服 盐山网页单机游戏 开封完美世界攻略 保康魔兽世界服务端 宜章魔域sf 建阳神魔大陆新闻 勃利天堂下载 南昌奇迹私服一条龙 湖口魔力宝贝sf 油嘴滑舌http://7777777777777.com,1.76传奇似服发布网o。热血传奇似服发布网欧美人体艺术摄影;而是你八字帖俄罗斯人体艺术‘性感人体艺术9传奇sf外挂传奇私服下载海枯石烂。贵州遵义县837962,七彩万劫奔走风尘无法言语;凤毛麟角椭圆形,穷山垩水传奇私服旁征博引,我們如何重新再來!z风言风语。河北乐亭455561,3英雄垂手可得比年不登;福寿无疆愁眉不展,闻名中外我会微笑,在痛苦中放纵着你的一切e哥不个性, 所以不需要个性签名。左半边幸福欢欣鼓舞,不知恩义r打顺风锣。
static/image/common/sigline.gif
http://www.43919.com,http://www.qq959.com传奇私服,
www.39ms.com减肥网,www.71TL.COM天龙八部私服
www.ms19.com魔兽世界私服,www.B5S5.COM左旋肉碱
www.LE76.COM广州开发票,www.WUQIJI.COM奇迹私服
www.04my.com魔域私服,www.zx40.com诛仙私服
www.939a.com小游戏
页:
[1]