Home > Web Front-end > JS Tutorial > Solve the garbled problem in remote page crawling? _javascript skills

Solve the garbled problem in remote page crawling? _javascript skills

WBOY
Release: 2016-05-16 19:18:20
Original
1082 people have browsed it

由于平时使用的网页文件基本上都是gb2312编码方式,如果通过xmlhttp控件读取的话,肯定会出现乱码问题,但是要把所有文件都改成utf-8编码,操作上比较麻烦。经过反复比较,我找到了相对实用的解决方法。

  ff提供了overrideMimeType方法,可以指定返回值的编码,所以解决起来比较简单,只要把这个方法指向gb2312就可以了。对于IE,可以用vbs配合来作编码转换,用gb2utf8来转换接收到的二进制数据,其中利用到execScript方法来调用vbs的函数。


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

ie下的转码可以改进,通过正则的回调过程能提高不少效率  

复制代码 代码如下:

this.bs2str = function(bs){  
    if(!window.jsMidB) main.vbInit("MidB", 2);  
    if(!window.jsChr) main.vbInit("Chr", 1);  
    if(!bs2str.ss) bs2str.ss = [];  
    return unescape(escape(jsMidB(bs,1)).replace(/(.{2})(.{2})(.{2})/g, "%$3%$2").replace(/%([^0-7].)(.)(.{2})/g, function(a,a1,a2,a3){var s=a1+a3;if(!bs2str.ss[s]) bs2str.ss[s]=jsChr(eval("0x"+s));return bs2str.ss[s];}));  
    } 

不过我还是认为载入数据用xmldom要好一些 
replace(/(.{2})(.{2})(.{2})/g, "%$3%$2") 改成 replace(/.{2}(.{2})(.{2})/g, "%$2%$1") 少一个存储.比原来的快3倍以上. 
把eval去掉,效率还能提高一些 
复制代码 代码如下:

    // byte() encoding 
    this.bs2str = function(bs){ 
        if(!window.jsMidB) main.vbInit("MidB", 2); 
        if(!window.jsChr) main.vbInit("Chr", 1); 
        if(!this.bs2str.ss) this.bs2str.ss = []; 
        return unescape(escape(jsMidB(bs,1)).replace(/.{2}(.{2})(.{2})/g, "%$2%$1").replace(/%([^0-7].)(.)(.{2})/g, function(a,a1,a2,a3){var s=a1+a3;if(!This.bs2str.ss[s]) This.bs2str.ss[s]=jsChr("&H"+s);return This.bs2str.ss[s];})); 
    }  
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template